简体   繁体   English

如何以各种格式格式化日期?

[英]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. 我今天注意到,在WP7上的Twitter应用程序中,显示了鸣叫并列出了它们的时间。 But, here is what I really liked: 但是,这是我真正喜欢的东西:

If a twit was made in the last few seconds, the listbox item displays for eg. 如果在过去的几秒钟内做出了twit,则列表框项目将显示例如。 5 secs ago. 5秒前。 If it was made in last few mintues, it shows for eg. 如果是在最后几分钟制作的,则显示为。 23 min ago. 23分钟前。 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). 这种格式适用于任何平台(Outlook执行类似的操作)。 Has anyone written an extension method or a helper function that they can share to achieve this kind of output? 是否有人编写了可以共享以实现这种输出的扩展方法或辅助函数?

Thanks, Pratik 谢谢,Pratik

Scott Mitchell had an article featured on the homepage of www.asp.net the other day which covered formatting dates. 前几天,斯科特·米切尔(Scott Mitchell)在www.asp.net的首页上刊登了一篇有关格式化日期的文章。

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() . 这篇文章是您可以使用的各种格式字符串的相当标准的文章,但其中约三分之二讨论了为解决此类问题而创建的自定义方法,称为.ToRelativeDateString() The implementation is included in the downloadable sample attached to the article: 该实现包含在本文所附的可下载示例中:

I am not sure if you are using java but PrettyTime is the library if you are. 我不确定您是否正在使用Java,但如果您使用的是PrettyTime,则为库。 You can also achieve this to certain extent using joda-time or its .net equvivalent noda-time . 您也可以使用joda-time或.net等价的noda-time在一定程度上实现这一目标。 Below is the eg of using joda-time to print 以下是使用joda-time打印的示例

On Tuesday at 2PM 星期二下午2点

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. 我实际上为此编写了一组类,这些类与.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. 例如,如果您是英语,则为“ 10秒前”,如果您具有瑞典文化背景,则为“ 10 sekunder sedan”。 It's that easy. 就这么简单。

You can download it at: 您可以在以下位置下载:

I18n Extensions - .NET4 Library I18n扩展-.NET4库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM