日期为.Net中的简单文本(例如,今天,昨天,1周前)

Tim*_*imS 7 .net string date date-format

有没有人有一个简单的功能可以将日期转换为简单的字符串(使用.Net)?

例如,2009年10月14日将会出现"今天",2009年10月13日会读到"昨天",而09年10月7日会读到"1周前"等等......

干杯,蒂姆

aol*_*lde 7

就像JustLoren说的那样,你确实必须采用自己的方法.

这是我一直在使用的扩展方法.它是将GateKiller脚本制作成扩展方法.如此完全归功于他.您可以轻松地将其更改为您想要的.

public static string ToTimeSinceString(this DateTime value)
{
    const int SECOND = 1;
    const int MINUTE = 60 * SECOND;
    const int HOUR = 60 * MINUTE;
    const int DAY = 24 * HOUR;
    const int MONTH = 30 * DAY;

    TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - value.Ticks);
    double seconds = ts.TotalSeconds;

    // Less than one minute
    if (seconds < 1 * MINUTE)
        return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";

    if (seconds < 60 * MINUTE)
        return ts.Minutes + " minutes ago";

    if (seconds < 120 * MINUTE)
        return "an hour ago";

    if (seconds < 24 * HOUR)
        return ts.Hours + " hours ago";

    if (seconds < 48 * HOUR)
        return "yesterday";

    if (seconds < 30 * DAY)
        return ts.Days + " days ago";

    if (seconds < 12 * MONTH) {
        int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
        return months <= 1 ? "one month ago" : months + " months ago";
    }

    int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
    return years <= 1 ? "one year ago" : years + " years ago";
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*ias 6

像这种扩展方法的东西?

public static string Stringfy(this DateTime date)
{
    if ((DateTime.Now - date.Date).TotalDays == 0)
        return "Today";

    if ((DateTime.Now - date.Date).TotalDays == 1)
        return "Yesterday";

    // ...

    return "A long time ago, in a galaxy far far away...";
}
Run Code Online (Sandbox Code Playgroud)