【问题标题】:Format DateTime like StackoverFlow [duplicate]像 StackoverFlow 一样格式化 DateTime [重复]
【发布时间】:2011-01-09 11:43:40
【问题描述】:

可能的重复:
Fuzzy date algorithm
How do I calculate relative time?

嗨,

如何像 SO 那样格式化日期时间?

1 分钟前

1 小时前

8 月 15 日 15:00 询问

【问题讨论】:

标签: c# datetime datetime-format


【解决方案1】:

您可能有兴趣将 jQuery's timeago plugin 移植到 C#

【讨论】:

    【解决方案2】:

    查看DateTime.ToString() Patterns。如果没有你喜欢的,你可以自己指定。

    【讨论】:

      【解决方案3】:

      您需要做的第一件事是确定日期的差异。

      在您的DateTime 上使用 Subtract() 方法。它返回一个TimeSpan,可以方便地满足您的需求。

      TimeSpan mySpan = DateTime.Now.Subtract( myPostedDate );
      

      然后,您需要找到最重要的非零时间元素。如果你正在处理几天,事情就很容易了。较小的面额需要更多的工作。包含代码。

      TimeSpan mySpan = DateTime.Now.Subtract(myRecorded);
      string  myDenom = 
        mySpan.Days    > 0 ? "day" : 
        mySpan.Hours   > 0 ? "hour" : 
        mySpan.Minutes > 0 ? "minute" : "second";
      
      string myOutput = String.Empty;
      
      int myNumeral;
      
      // if we're dealing with days, a format string will suffice
      if (myDenom == "day")
      {
          // HH - 24 hour clock
          myOutput = String.Format("{0:MMM dd} at {0:HH}:{0:mm}", myRecorded);
      }
      else
      {
          // put the right denomination into myNumeral
          switch (myDenom)
          {
              case "second":
                  myNumeral = mySpan.Seconds;
                  break;
              case "minute":
                  myNumeral = mySpan.Minutes;
                  break;
              default:
                  myNumeral = mySpan.Hours;
                  break;
          }
      
          // add an s to myNumeral when > 1
          myDenom += (myNumeral > 1) ? "s" : String.Empty;
          myOutput = String.Format("{0} {1} ago", myNumeral, myDenom);
      }
      
      // myOutput now contains formatted string
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        相关资源
        最近更新 更多