根据当前的日期获取到周起始,月起始,年起始
一、根据当前的日期获取到周起始和截止
1 /// <summary> 2 /// 得到本周第一天(以星期天为第一天) 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public DateTime GetWeekFirstDaySun(DateTime datetime) 7 { 8 //星期天为第一天 9 int weeknow = Convert.ToInt32(datetime.DayOfWeek); 10 int daydiff = (-1) * weeknow; 11 12 //本周第一天 13 string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); 14 return Convert.ToDateTime(FirstDay); 15 }
1 /// <summary> 2 /// 得到本周第一天(以星期一为第一天) 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public DateTime GetWeekFirstDayMon(DateTime datetime) 7 { 8 //星期一为第一天 9 int weeknow = Convert.ToInt32(datetime.DayOfWeek); 10 11 //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。 12 weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1)); 13 int daydiff = (-1) * weeknow; 14 15 //本周第一天 16 string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); 17 return Convert.ToDateTime(FirstDay); 18 }
1 /// <summary> 2 /// 得到本周最后一天(以星期六为最后一天) 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public DateTime GetWeekLastDaySat(DateTime datetime) 7 { 8 //星期六为最后一天 9 int weeknow = Convert.ToInt32(datetime.DayOfWeek); 10 int daydiff = (7 - weeknow) - 1; 11 12 //本周最后一天 13 string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); 14 return Convert.ToDateTime(LastDay); 15 }
1 /// <summary> 2 /// 得到本周最后一天(以星期天为最后一天) 3 /// </summary> 4 /// <param name="datetime"></param> 5 /// <returns></returns> 6 public DateTime GetWeekLastDaySun(DateTime datetime) 7 { 8 //星期天为最后一天 9 int weeknow = Convert.ToInt32(datetime.DayOfWeek); 10 weeknow = (weeknow == 0 ? 7 : weeknow); 11 int daydiff = (7 - weeknow); 12 13 //本周最后一天 14 string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); 15 return Convert.ToDateTime(LastDay); 16 }
二、根据当前的日期获取到月起始和截止
int year = DateTime.Now.Year; int month = DateTime.Now.Month; DateTime firstDayOfThisMonth = new DateTime(year, month, 1); DateTime lastDayOfThisMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));
SQL语句实现
1 DECLARE @NOW DATETIME 2 DECLARE @FistDayOfThisMonth DATETIME 3 DECLARE @LastDayOfThisMonth DATETIME 4 5 SET @NOW = GETDATE() 6 SET @FistDayOfThisMonth = @NOW - DAY(@NOW) + 1 7 SET @LastDayOfThisMonth = DATEADD(MONTH, 1, @NOW - DAY(@NOW) + 1) - 1 8 9 SELECT @FistDayOfThisMonth 10 SELECT @LastDayOfThisMonth
三、根据当前的日期获取到年起始和截止
1 int year = DateTime.Now.Year; 2 int month = DateTime.Now.Month; 3 4 DateTime firstDayOfThisMonth = new DateTime(year, 1, 1); 5 DateTime lastDayOfThisMonth = new DateTime(year, 12, DateTime.DaysInMonth(year, 12));