482 字 ~ 2 分钟阅读

如何使用?

HumanizeTime(string date) 函数,传入时间格式的字符串即可。如:HumanizeTime(“2010-12-21”);
注意: 传入的时间要小于当前的时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/// <summary>
/// 把两个时间差,用人性化时间表示
/// </summary>
/// 被比较的时间</param>
/// 目标时间</param>
/// <returns></returns>
public static string ConvertDateTime(string date, DateTime currentDateTime)
{
if (Utils.StrIsNullOrEmpty(date))
return "";

DateTime time;
if (!DateTime.TryParse(date, out time))
return date;

string result = "";

if (DateDiff("year", time, currentDateTime) > 0)
{
return DateDiff("year", time, currentDateTime) + "年前";
}
else if (DateDiff("month", time, currentDateTime) < 12 && DateDiff("month", time, currentDateTime) > 0)
{
return DateDiff("month", time, currentDateTime) + "月前";
}
else if (DateDiff("day", time, currentDateTime) < 30 && DateDiff("day", time, currentDateTime) > 0)
{
return DateDiff("day", time, currentDateTime) + "天前";
}
else if (DateDiff("hour", time, currentDateTime) < 24)
{
if (DateDiff("hour", time, currentDateTime) > 0)
return DateDiff("hour", time, currentDateTime) + "小时前";

if (DateDiff("minute", time, currentDateTime) > 0)
return DateDiff("minute", time, currentDateTime) + "分钟前";
else
return "刚才";
}
else
result = time.ToString("yyyy-MM-dd HH:mm");
return result;
}

/// <summary>
/// 两个时间的差值,可以为秒,小时,天,分钟
/// </summary>
/// 需要得到的时差方式</param>
/// 起始时间</param>
/// 结束时间</param>
/// <returns></returns>
public static long DateDiff(string Interval, DateTime StartDate, DateTime EndDate)
{

long lngDateDiffValue = 0;
System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
switch (Interval)
{
case "second":
lngDateDiffValue = (long)TS.TotalSeconds;
break;
case "minute":
lngDateDiffValue = (long)TS.TotalMinutes;
break;
case "hour":
lngDateDiffValue = (long)TS.TotalHours;
break;
case "day":
lngDateDiffValue = (long)TS.Days;
break;
case "week":
lngDateDiffValue = (long)(TS.Days / 7);
break;
case "month":
lngDateDiffValue = (long)(TS.Days / 30);
break;
case "quarter":
lngDateDiffValue = (long)((TS.Days / 30) / 3);
break;
case "year":
lngDateDiffValue = (long)(TS.Days / 365);
break;
}
return (lngDateDiffValue);
}

/// <summary>
/// 转换时间为人性化时间
/// </summary>
/// 被转换的时间</param>
/// <returns></returns>
public static string HumanizeTime(string date)
{
return ConvertDateTime(date, DateTime.Now);
}