Possible Duplicates:
Fuzzy date algorithm
How do I calculate relative time?
嗨,
如何像这样格式化日期时间?
1分钟前
1小时前
8 月 15 日 15:00 提问
最佳答案
您需要做的第一件事是确定日期的差异。
在 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
关于c# - 像 StackoverFlow 一样设置日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2139022/