1: /// <summary>
2: /// 格式化显示时间为几个月,几天前,几小时前,几分钟前,或几秒前
3: /// </summary>
4: /// <param name="dt">要格式化显示的时间</param>
5: /// <returns>几个月,几天前,几小时前,几分钟前,或几秒前</returns>
6: public static string DateStringFromNow(DateTime dt)
7: {
8: TimeSpan span = DateTime.Now - dt;
9: if (span.TotalDays > 60)
10: {
11: return dt.ToShortDateString();
12: }
13: else if (span.TotalDays > 30)
14: {
15: return "1个月前";
16: }
17: else if (span.TotalDays > 14)
18: {
19: return "2周前";
20: }
21: else if (span.TotalDays > 7)
22: {
23: return "1周前";
24: }
25: else if (span.TotalDays > 1)
26: {
27: return string.Format("{0}天前", (int)Math.Floor(span.TotalDays));
28: }
29: else if (span.TotalHours > 1)
30: {
31: return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
32: }
33: else if (span.TotalMinutes > 1)
34: {
35: return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
36: }
37: else if (span.TotalSeconds >= 1)
38: {
39: return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
40: }
41: else
42: {
43: return "1秒前";
44: }
45: }
46: