# 求计算时间差值方法？

0
[已解决问题] 解决于 2007-12-04 11:34
<P>在该社区提问后，表示的1分钟前，7天前，一周前，一个月前，等，这些通过时间计算方法，有没有简便的？</P>

1
castle monorail里自带两个方法，分别是： public String AlternativeFriendlyFormatFromNow(DateTime date)， public String FriendlyFormatFromNow(DateTime date) 代码如下，希望对你有帮助：） public String AlternativeFriendlyFormatFromNow(DateTime date) { TimeSpan now = new TimeSpan(DateTime.Now.Ticks); TimeSpan cur = new TimeSpan(date.Ticks); TimeSpan diff = now.Subtract(cur); if (diff.TotalHours <= 24) { return "Today"; } else if (diff.TotalHours <= 48) { return "Yesterday"; } else if (diff.TotalDays <= 40) { return String.Format("{0} days ago", diff.Days); } else { return String.Format("{0} months ago", (diff.Days / 30)); } } /// <summary> /// Returns the difference from the /// specified <c>date</c> the the current date /// in a friendly string like "1 day ago" /// <para> /// TODO: Think about i18n /// </para> /// </summary> /// <param name="date">The date in the past (should be equal or less than now)</param> /// <returns></returns> public String FriendlyFormatFromNow(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" :

0

Jeffrey Zhao | 园豆：1629 (小虾三级) | 2007-11-29 13:35
0

Dev.Hong | 园豆：415 (菜鸟二级) | 2007-11-29 16:06
0
.NET的DateTime结构支持加减运算，结果返回一个TimeSpan结构，TimeSpan自带相应字段

0
.NET有自己的类可以实现对时间的差值计算,具体是什么你可以msdn一下.

0
1分钟前，7天前，一周前，一个月前 不知道我题意是否理解正确了…… 写一个类，可能要有个 public class Description {Description(DateTime time){} string GetTimeDescText()} 然后根据你的TimeSpan进行判断，回复一个(1分钟前，7天前，一周前，一个月前) 以后只用Description desc = new Description(DateTime.Now); desc.GetTimeDescText();
volnet（可以叫我大V） | 园豆：720 (小虾三级) | 2007-11-29 18:57
0

wingoo | 园豆：1513 (小虾三级) | 2007-11-29 19:46
0

niugm | 园豆：1685 (小虾三级) | 2007-11-30 09:26
0

guogu82 | 园豆：365 (菜鸟二级) | 2007-12-01 08:24

您需要登录以后才能回答，未注册用户请先注册