友好的日期及时间显示
使用使用友好的日期显示会有较好的用户体验。非常适合新闻类的网站。
文章发布距当前时间1小时内的,显示n分钟前。
1天内的,显示小时数。
2天和3天的,显示昨天和前天。
7天内的显示,n天前。
其他的显示日期
以下是C#代码:
- public static string FriendlyDate(Object sdate)
- {
- DateTime date = Convert.ToDateTime(sdate);
- DateTime now = DateTime.Now;
- int day = DateTime.Now.Date.Subtract(date).Days;
- //1天内
- if (day < 1)
- {
- int hour = (now.Subtract(date)).Hours;
- if (hour > 1)
- {
- return hour + "小时前";
- }
- else
- {
- //1小时内
- int minute = (now.Subtract(date)).Minutes;
- if (minute > 0)
- {
- return minute + "分钟前";
- }
- }
- return date.ToShortDateString();
- }
- //昨天
- else if (day == 1)
- {
- return "昨天";
- }
- //前天
- else if (day == 2)
- {
- return "前天";
- }
- //4-7天
- else if (day >= 3 && day <= 7)
- {
- return day + "天前";
- }
- else
- {
- return date.ToShortDateString();
- }
- }
