计算文章发表时间段

在论坛,微博里面经常会看到贴子,微博的发布时间显示的是,几天以前,几个小时以前,几分钟以前,几秒以前等统计

下面是一个计算距离发表时刻时间段的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String CalculateTime_1(DateTime date)
{
TimeSpan now = new TimeSpan(DateTime.Now.Ticks);
TimeSpan cur = new TimeSpan(date.Ticks);
TimeSpan diff = now.Subtract(cur);
if (diff.TotalHours {
return "Today";
}
else if (diff.TotalHours {
return "Yesterday";
}
else if (diff.TotalDays {
return String.Format("{0} days ago", diff.Days);
}
else
{
return String.Format("{0} months ago"(diff.Days / 30));
}
}
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
public String CalculateTime_2(DateTime date)
{
TimeSpan now = new TimeSpan(DateTime.Now.Ticks);
TimeSpan cur = new TimeSpan(date.Ticks);
TimeSpan diff = now.Subtract(cur);
if (diff.TotalSeconds == 0)
{
return "Just now";
}
if (diff.Days == 0)
{
if (diff.Hours == 0)
{
if (diff.Minutes == 0)
{
return String.Format("{0} second{1} ago", diff.Seconds, diff.Seconds > 1 ? "s" : String.Empty);
}
else
{
return String.Format("{0} minute{1} ago", diff.Minutes, diff.Minutes > 1 ? "s" : String.Empty);
}
}
else
{
return String.Format("{0} hour{1} ago", diff.Hours, diff.Hours > 1 ? "s" : String.Empty);
}
}
else
{
return String.Format("{0} day{1} ago", diff.Days, diff.Days > 1 ? "s" : String.Empty);
}
}
原文地址:https://www.cnblogs.com/ganler1988/p/3023483.html