原文:
编程乐趣:C#获取日期所在周、月份第一和最后一天
写了个小功能,需要用到以周为时间段,于是写了个获取周第一和最后一天的方法,获取月份的第一和最后一天就比较简单了。代码如下:
public class DateTimeTool { /// <summary> /// 获取指定日期所在周的第一天,星期天为第一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime) { DateTime firstWeekDay = DateTime.Now; try { //得到是星期几,然后从当前日期减去相应天数 int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = (-1) * weeknow; firstWeekDay = dateTime.AddDays(daydiff); } catch { } return firstWeekDay; } /// <summary> /// 获取指定日期所在周的第一天,星期一为第一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime) { DateTime firstWeekDay = DateTime.Now; try { int weeknow = Convert.ToInt32(dateTime.DayOfWeek); //星期一为第一天,weeknow等于0时,要向前推6天。 weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1)); int daydiff = (-1) * weeknow; firstWeekDay = dateTime.AddDays(daydiff); } catch { } return firstWeekDay; } /// <summary> /// 获取指定日期所在周的最后一天,星期六为最后一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime) { DateTime lastWeekDay = DateTime.Now; try { int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = (7 - weeknow) - 1; lastWeekDay = dateTime.AddDays(daydiff); }catch { } return lastWeekDay; } /// <summary> /// 获取指定日期所在周的最后一天,星期天为最后一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime) { DateTime lastWeekDay = DateTime.Now; try { int weeknow = Convert.ToInt32(dateTime.DayOfWeek); weeknow = (weeknow == 0 ? 7 : weeknow); int daydiff = (7 - weeknow); lastWeekDay = dateTime.AddDays(daydiff); } catch { } return lastWeekDay; } /// <summary> /// 获取指定日期的月份第一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeMonthFirstDay(DateTime dateTime) { if (dateTime == null) { dateTime = DateTime.Now; } return new DateTime(dateTime.Year, dateTime.Month, 1); } /// <summary> /// 获取指定月份最后一天 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public static DateTime GetDateTimeMonthLastDay(DateTime dateTime) { int day = DateTime.DaysInMonth(dateTime.Year, dateTime.Month); return new DateTime(dateTime.Year, dateTime.Month, day); } }