开发者

how to format the date in various formats?

I noticed today that in my twitter app on WP7, the twits are shown and their times are listed. But, here is what I really liked:

If a twit was made in the last few seconds, the listbox item displays for eg. 5 secs ago. If it was made in last few mintues, it shows for eg. 23 min ago. Same way, shows the word today If it was on any prior dates, it shows the actual date time.

开发者_运维百科

This type of formatting would apply to any platform (Outlook does similar things). Has anyone written an extension method or a helper function that they can share to achieve this kind of output?

Thanks, Pratik


Scott Mitchell had an article featured on the homepage of www.asp.net the other day which covered formatting dates.

The article was a pretty standard run through of the various formatting strings you can use but about two thirds in he discusses a custom method he has created to solve this kind of problem called .ToRelativeDateString(). The implementation is included in the downloadable sample attached to the article:

  • https://web.archive.org/web/20211020131217/https://www.4guysfromrolla.com/articles/111010-1.aspx


I am not sure if you are using java but PrettyTime is the library if you are. You can also achieve this to certain extent using joda-time or its .net equvivalent noda-time. Below is the e.g. of using joda-time to print

On Tuesday at 2PM

DateTime dt = new DateTime(2005, 9, 20, 14, 30, 0, 0);
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendLiteral(“On “)
.appendDayOfWeekText()
.appendLiteral(“ at “)
.appendClockhourOfHalfday(1)
.appendHalfdayOfDayText()
.toFormatter();

String str = f.print(dt);
// Output: On Tuesday at 2PM


I actually wrote a set of classes for this, which integrates with the internationalization in .NET. Since its tied to the culture, you can easily have different variations. Eg "10 seconds ago" if you're English, or "10 sekunder sedan" if you have the Swedish culture set. It's that easy.

You can download it at:

I18n Extensions - .NET4 Library

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜