人类可读的日期格式
您可能已经注意到,某些 Web 应用程序(例如 GMail 的某些部分)以比简单的 DD/MM/YYYY 更易于理解的格式显示日期。
例如,如果我从 23 日(撰写本文时恰好是 3 天前)打开一封邮件,我将收到以下内容:
12月23日(3天前)
我想在我自己的 Web 应用程序中实现与此类似的逻辑。
例如,在处理 .NET TimeSpan 对象时,我想将其转换为如下文本:
2个月
3天
是否有 .NET 库能够做到这一点?
如果没有,我可能会构建一些基本的东西并将其开源。
我在这里做了一个基本的开始:
public static class TimeSpanHelpers
{
public static string ToHumanReadableString(
this TimeSpan timeSpan)
{
if (timeSpan.TotalDays > 30)
return (timeSpan.TotalDays / 30) + " month(s)";
if (timeSpan.TotalDays > 7)
return (timeSpan.TotalDays / 7) + " week(s)";
return (timeSpan.TotalDays) + " day(s)";
}
}
You may have noticed that certain web applications (for example, certain parts of GMail) display dates in a more human-readable format than simply DD/MM/YYYY.
For example, if I open up a mail item from the 23rd (which happens to be 3 days ago at the time of writing, I'll get the following:
Dec 23 (3 days ago)
I'd like to implement similar logic to this in my own web application.
For example, when dealing with a .NET TimeSpan object, I'd like to convert it to text such as the following:
2 months
3 days
Is there a .NET library capable of doing this already?
If not I might build something basic and open-source it.
I've made a basic start here:
public static class TimeSpanHelpers
{
public static string ToHumanReadableString(
this TimeSpan timeSpan)
{
if (timeSpan.TotalDays > 30)
return (timeSpan.TotalDays / 30) + " month(s)";
if (timeSpan.TotalDays > 7)
return (timeSpan.TotalDays / 7) + " week(s)";
return (timeSpan.TotalDays) + " day(s)";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试 Humanizer http:// humanizr.net/
Nuget:
Try Humanizer http://humanizr.net/
Nuget:
Noda Time 小组正致力于实现这一目标。过来一起享受乐趣吧。忘记提及项目位置 Noda Time 项目
The Noda Time group is in the process of doing just this. Come on over and join the fun. Forgot to mention the project location Noda Time project
另一个用于执行此操作的库: http://relativetime.codeplex.com/
(在 NuGet 上提供)
Another library for doing this: http://relativetime.codeplex.com/
(Available on NuGet)
我最终使用了此方法,因为我需要支持未来的日期,例如从现在开始的 3 天。
I ended up using this method as I needed to support future dates like 3 days from now.