时间,日期的使用(公共方法)
1 public class TimeHelper 2 { 3 #region 实现发表的时间显示 4 /// <summary> 5 /// 实现发表的时间显示为几个月,几天前,几小时前,几分钟前,或几秒前 6 /// </summary> 7 /// <param name="time"></param> 8 /// <returns></returns> 9 public static string DateStringFromNow(DateTime time) 10 { 11 TimeSpan span = DateTime.Now - time; 12 if (span.TotalDays > 120) 13 { 14 return time.ToShortDateString(); 15 } 16 else if (span.TotalDays > 90) 17 { 18 return "3个月前"; 19 } 20 else if (span.TotalDays > 60) 21 { 22 return "2个月前"; 23 } 24 else if (span.TotalDays > 30) 25 { 26 return "1个月前"; 27 } 28 else if (span.TotalDays > 14) 29 { 30 return "2周前"; 31 } 32 else if (span.TotalDays > 7) 33 { 34 return "1周前"; 35 } 36 else if (span.TotalDays > 1) 37 { 38 return string.Format("{0}天前", (int)Math.Floor(span.TotalDays)); 39 } 40 else if (span.TotalHours > 1) 41 { 42 return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours)); 43 } 44 else if (span.TotalMinutes > 1) 45 { 46 return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes)); 47 } 48 else if (span.TotalSeconds >= 1) 49 { 50 return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds)); 51 } 52 else 53 { 54 return "1秒前"; 55 } 56 } 57 #endregion 58 59 #region 根据指定的日期获取当前的星期一日期 60 /// <summary> 61 /// 根据指定的日期获取当前的星期一日期 62 /// </summary> 63 /// <param name="dateTime"></param> 64 /// <returns></returns> 65 public static DateTime GetMondayDate(DateTime dateTime) 66 { 67 int dd = Convert.ToInt32(dateTime.DayOfWeek); 68 if (dd == 0) dd = 7; 69 return dateTime.AddDays(-dd + 1); 70 } 71 #endregion 72 73 #region 获取指定日期获取当前的星期天日期 74 /// <summary> 75 /// 获取指定日期获取当前的星期天日期 76 /// </summary> 77 /// <param name="dateTime"></param> 78 /// <returns></returns> 79 public static DateTime GetSundayDate(DateTime dateTime) 80 { 81 return dateTime.AddDays(1 - Convert.ToInt32(dateTime.DayOfWeek.ToString("d"))).AddDays(6); 82 } 83 #endregion 84 85 #region 获取两者间的相隔天数 86 /// <summary> 87 /// 获取两者间的相隔天数 88 /// </summary> 89 /// <param name="beginDate"></param> 90 /// <param name="endDate"></param> 91 /// <returns></returns> 92 public static int GetApartDay(DateTime beginDate, DateTime endDate) 93 { 94 TimeSpan span = endDate - beginDate; 95 return Convert.ToInt32(span.TotalDays); 96 } 97 #endregion 98 99 }