【问题标题】:Format .Net datetime in descriptive text format like "Last Month"?以描述性文本格式格式化.Net日期时间,如“上个月”?
【发布时间】:2012-06-08 10:07:59
【问题描述】:

.Net 或任何 Nuget 包中是否有任何功能可以将时间以描述性格式描述过去有多远。

例如给定一个日期,说出过去的情况。

  • 昨天
  • 5 天前
  • 上周
  • 上个月
  • 4 个月前
  • 去年

我在 Perl 中看到过类似的东西,我不想重新发明轮子

【问题讨论】:

    标签: .net datetime datetime-format


    【解决方案1】:

    您可以安装this NuGet 包,您将拥有一个DateTime.ToNaturalRelativeTime 扩展方法,似乎可以满足您的要求。

    【讨论】:

      【解决方案2】:

      在 .NET 上没有内置方法可以做到这一点,但制作扩展方法很简单(来自this question 的想法,由 Vincent Robert 和 Jeff Atwood 提出):

      public static string AsRelative(this DateTime dt) {
          var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
          double delta = Math.Abs(ts.TotalSeconds);
          const int SECOND = 1;
          const int MINUTE = 60 * SECOND;
          const int HOUR = 60 * MINUTE;
          const int DAY = 24 * HOUR;
          const int MONTH = 30 * DAY;
      
          if (delta < 0)
          {
            return "not yet";
          }
          if (delta < 1 * MINUTE)
          {
            return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
          }
          if (delta < 2 * MINUTE)
          {
            return "a minute ago";
          }
          if (delta < 45 * MINUTE)
          {
            return ts.Minutes + " minutes ago";
          }
          if (delta < 90 * MINUTE)
          {
            return "an hour ago";
          }
          if (delta < 24 * HOUR)
          {
            return ts.Hours + " hours ago";
          }
          if (delta < 48 * HOUR)
          {
            return "yesterday";
          }
          if (delta < 30 * DAY)
          {
            return ts.Days + " days ago";
          }
          if (delta < 12 * MONTH)
          {
            int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
            return months <= 1 ? "one month ago" : months + " months ago";
          }
          else
          {
            int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
            return years <= 1 ? "one year ago" : years + " years ago";
          }
      }
      

      【讨论】:

      • 我在搜索时只需要知道将其称为自然时间或相对时间。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2017-02-16
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      相关资源
      最近更新 更多