这是今天做一个计划统计写的一个简单算法,通过年,月,周计算出本周有哪些天,测试效果图如下:
第一步:获取本月第一周第一个工作日
View Code
1 ///2 /// 获取本月第一周第一个工作日 3 /// 4 /// 本月一号在这一周星期几 5 ///本月第一周第一个工作日 6 private int GetFirstWeekDayWithMonth(DayOfWeek weekEnum) 7 { 8 if (weekEnum.GetHashCode() == 1) 9 return 1; 10 else if (weekEnum.GetHashCode() == 0) 11 return 2; 12 else 13 return 7 - weekEnum.GetHashCode() + 2; 14 }
第二步:获取本月最后一个工作日
View Code
1 ///2 /// 获取本月最后一天 3 /// 4 /// 年 5 /// 月 6 ///本月最后一个工作日 7 private int GetLastDayWithMonth(int year, int month) 8 { 9 int maxDay = 1; 10 switch (month) 11 { 12 case 1: 13 case 3: 14 case 5: 15 case 7: 16 case 8: 17 case 10: 18 case 12: 19 maxDay = 31; 20 break; 21 case 2: 22 if (year % 4 == 0) maxDay = 29; else maxDay = 28; 23 break; 24 case 4: 25 case 6: 26 case 9: 27 case 11: 28 maxDay = 30; 29 break; 30 default: 31 return maxDay; 32 } 33 return maxDay; 34 }
第三步:计算
View Code
1 ///2 /// 根据年月周计算时间 3 /// 4 /// 年 5 /// 月 6 /// 周 7 ///DateTime[]时间 8 public DateTime[] GetDaysByWeekAndMont(int year, int month, int week) 9 { 10 int firstDay = 0; 11 DateTime[] days = new DateTime[] { new DateTime() }; 12 if (month < 13 && week < 6) 13 { 14 DateTime date = new DateTime(year, month, 1); 15 firstDay = GetFirstWeekDayWithMonth(date.DayOfWeek) + 7 * (week - 1); 16 if (firstDay <= GetLastDayWithMonth(year, month)) 17 { 18 days = new DateTime[7]; 19 for (int i = 0; i < 7; i++) 20 { 21 if (firstDay <= GetLastDayWithMonth(year, month) && month < 13) 22 days[i] = new DateTime(year, month, firstDay++); 23 else if (firstDay >= GetLastDayWithMonth(year, month) && month < 13) 24 { 25 firstDay = 1; 26 if (month != 12) 27 days[i] = new DateTime(year, ++month, firstDay++); 28 else 29 { 30 month = 1; 31 days[i] = new DateTime(++year, month++, firstDay++); 32 } 33 } 34 else if (firstDay <= GetLastDayWithMonth(year, month) && month > 12) 35 { 36 days[i] = new DateTime(year, month, firstDay++); 37 } 38 else if (firstDay >= GetLastDayWithMonth(year, month) && month > 12) 39 { 40 month = 1; firstDay = 1; 41 days[i] = new DateTime(year, month++, firstDay++); 42 } 43 } 44 } 45 else 46 throw new Exception(year.ToString() + "年" + month + "月没有第" + week + "周"); //Console.WriteLine("输入时间错误"); 47 } 48 else if (month > 12 ) 49 throw new Exception(year + "年没有" + month + "月");//Console.WriteLine("输入时间错误"); 50 else if (month < 13 && week > 5) 51 throw new Exception(year + "年" + month + "月没有第" + week + "周"); 52 return days; 53 }