人类可读的日期格式

Jon*_*han 10 .net c# timespan user-experience date

您可能已经注意到某些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)";
    }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*am7 12

尝试Humanizer http://humanizr.net/

TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"

// in de-DE culture
TimeSpan.FromDays(1).Humanize() => "Ein Tag"
TimeSpan.FromDays(2).Humanize() => "2 Tage"

// in sk-SK culture
TimeSpan.FromMilliseconds(1).Humanize() => "1 milisekunda"

// and a lot more
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
"case".ToQuantity(5) => "5 cases"
"man".ToQuantity(2) => "2 men"
122.ToWords() => "one hundred and twenty-two"
(.5).Gigabytes().Humanize() => "512 MB"
"Long text to truncate".Truncate(10) => "Long text…",
"Sentence casing".Transform(To.TitleCase) => "Sentence Casing"
Run Code Online (Sandbox Code Playgroud)

的NuGet:

Install-Package Humanizer
Run Code Online (Sandbox Code Playgroud)


Jam*_*sey 7

野田佳彦时间组是在做眼前这个过程.快来加入吧.忘了提到Noda Time项目的项目位置

  • 看起来很酷。您能给我们一个想法,在Node Time项目中应该看什么。 (2认同)