处理当前时间跟历史时间,显示相对时间
给定一个特定DateTime值,我如何显示相对时间,例如:
- 2小时前
- 3天前
- 一个月前
学到一个方法,巧妙的对比
public static string RelativeDate(DateTime theDate)
{
string result = string.Empty;
Dictionary<long, string> thresholds = new Dictionary<long, string>();
int minute = 60;
int hour = 60 * minute;
int day = 24 * hour;
thresholds.Add(60, "{0} seconds ago");
thresholds.Add(minute * 2, "a minute ago");
thresholds.Add(45 * minute, "{0} minutes ago");
thresholds.Add(120 * minute, "an hour ago");
thresholds.Add(day, "{0} hours ago");
thresholds.Add(day * 2, "yesterday");
thresholds.Add(day * 29, "{0} days ago");
thresholds.Add(day * 30, "{0} month ago");
thresholds.Add(day * 30 * 12, "{0} months ago");
thresholds.Add(day * 30 * 12 * 2, "a year ago");
thresholds.Add(long.MaxValue, "{0} years ago");
long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;
foreach (long threshold in thresholds.Keys)
{
if (since < threshold)
{
TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));
return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 30 ? t.Days / 30 : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());
}
}
return "";
}
浙公网安备 33010602011771号