需要帮助修改以非正式方式显示日期的方法
本文关键字:显示 日期 方法 方式 非正式 帮助 修改 | 更新日期: 2023-09-27 18:07:00
如果日期是几个月前或一年以前,则下面的方法返回null。如果我想将日期显示为"2个月前"或"1年前"。我应该如何修改下面的方法?
// 1.
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// 2.
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0 || dayDiff >= 31)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return null;
}
在if块之后:if (dayDiff < 31) { ... }
插入以下代码:
if (dayDiff < 365)
{
return string.Format("{0} month(s) ago", Math.Ceiling((double)dayDiff / 31));
}
else
{
return string.Format("{0} year(s) ago", Math.Ceiling((double)dayDiff / 365));
}
你可以直接比较TimeSpans:
TimeSpan s = DateTime.Now.Subtract(d);
if (s < TimeSpan.FromDays(1))
{
// ...
}
else if (s < TimeSpan.FromMonth(1))
{
// ...
}
// ...
按你想要的方式组合(抱歉,我无法从你的问题中解析)我想你可能会喜欢:
TimeSpan s = DateTime.Now.Subtract(d);
if (s < TimeSpan.FromDays(1))
{
return string.Format("{0:0} hour(s) ago", s.TotalHours);
}
else if (s < TimeSpan.FromDays(7))
{
return string.Format("{0:0} day(s) ago", s.TotalDays);
}
// ...