C#获取指定月指定周的日期范围 根据当前时间获取本月开始日期和结束日期

来源:互联网 发布:淘宝衣服模特招聘要求 编辑:程序博客网 时间:2024/04/28 13:41
[csharp] view plaincopyprint?
  1. /// <summary>  
  2. /// 获取指定月份指定周数的开始日期  
  3. /// </summary>  
  4. /// <param name="year">年份</param>  
  5. /// <param name="month">月份</param>  
  6. /// <param name="index">周数</param>  
  7. /// <returns></returns>  
  8. private DateTime GetStartDayOfWeeks(int year, int month, int index)  
  9. {  
  10.     if (year < 1600 || year > 9999)  
  11.     {  
  12.         MessageBox.Show("年份超限");  
  13.         return DateTime .MinValue ;  
  14.     }  
  15.     if (month < 0 || month > 12)  
  16.     {  
  17.         MessageBox.Show("月份错误");  
  18.         return DateTime .MinValue ;  
  19.     }  
  20.     if (index < 1)  
  21.     {  
  22.         MessageBox.Show("周数错误");  
  23.         return DateTime.MinValue;  
  24.     }  
  25.     DateTime startMonth = new DateTime(year, month, 1);  //该月第一天  
  26.     int dayOfWeek = 7;  
  27.     if (Convert.ToInt32(startMonth.DayOfWeek.ToString("d")) > 0)  
  28.         dayOfWeek = Convert.ToInt32(startMonth.DayOfWeek.ToString("d"));  //该月第一天为星期几  
  29.     DateTime startWeek = startMonth.AddDays(1 - dayOfWeek);  //该月第一周开始日期  
  30.     //DateTime startDayOfWeeks = startWeek.AddDays((index - 1) * 7);  //index周的起始日期  
  31.     DateTime startDayOfWeeks = startWeek.AddDays(index * 7);  //index周的起始日期  
  32.     if ((startDayOfWeeks - startMonth.AddMonths(1)).Days > 0)  //startDayOfWeeks不在该月范围内  
  33.     {  
  34.         MessageBox.Show("输入周数大于本月最大周数");  
  35.         return DateTime.MinValue;  
  36.     }  
  37.     return startDayOfWeeks;  
  38. }  


 

[csharp] view plaincopyprint?
  1. //当前时间  
  2. DateTime dt = DateTime.Now;  
  3. //本月第一天时间      
  4. DateTime dt_First = dt.AddDays(1 - (dt.Day));  
  5. //获得某年某月的天数    
  6. int year = dt.Date.Year;  
  7. int month = dt.Date.Month;  
  8. int dayCount = DateTime.DaysInMonth(year, month);  
  9. //本月最后一天时间    
  10. DateTime dt_Last = dt_First.AddDays(dayCount - 1);