寫了個小功能,需要用到以周為時間段,於是寫了個擷取周第一和最後一天的方法,擷取月份的第一和最後一天就比較簡單了。代碼如下:
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); } }