1. 不允许跨年
1) 第一周的第一天从每年的第一天开始,最后一周的最后一天为每年的最后一天。
1 static void Main(string[] args) 2 { 3 DateTime first, last; 4 int[] years = new int[] { 2015, 2016, 2017, 2018 }; 5 int[] weeks = new int[] { 1, 52, 53 }; 6 foreach (int y in years) 7 { 8 foreach (int w in weeks) 9 { 10 bool result = CalcWeekDay(y, w, out first, out last); 11 Console.WriteLine("{0}第{1}周({2:yyyy-MM-dd} ~ {3:yyyy-MM-dd}) --{4}", y, w, first, last, result); 12 } 13 Console.WriteLine(); 14 } 15 } 16 17 public static bool CalcWeekDay(int year, int week, out DateTime first, out DateTime last) 18 { 19 first = DateTime.MinValue; 20 last = DateTime.MinValue; 21 //年份超限 22 if (year < 1700 || year > 9999) return false; 23 //周数错误 24 if (week < 1 || week > 53) return false; 25 //指定年范围 26 DateTime start = new DateTime(year, 1, 1); 27 DateTime end = new DateTime(year, 12, 31); 28 int startWeekDay = (int)start.DayOfWeek; 29 30 if (week == 1) 31 { 32 first = start; 33 last = start.AddDays(6 - startWeekDay); 34 } 35 else 36 { 37 //周的起始日期 38 first = start.AddDays((7 - startWeekDay) + (week - 2) * 7); 39 last = first.AddDays(6); 40 if (last > end) 41 { 42 last = end; 43 } 44 } 45 return (first <= end);
2) 程序执行结果
2. 允许跨年
1) 每年的尾周剩余天数计入下一年第一周。
1 public static bool CalcWeekDay(int year, int week, out DateTime first, out DateTime last) 2 { 3 first = DateTime.MinValue; 4 last = DateTime.MinValue; 5 //年份超限 6 if (year < 1700 || year > 9999) return false; 7 //周数错误 8 if (week < 1 || week > 53) return false; 9 //指定年范围 10 DateTime start = new DateTime(year, 1, 1); 11 DateTime end = new DateTime(year, 12, 31); 12 int startWeekDay = (int)start.DayOfWeek; 13 //周的起始日期 14 first = start.AddDays((7 - startWeekDay) + (week - 2) * 7); 15 last = first.AddDays(6); 16 //结束日期跨年 17 return (last <= end); 18 }
2) 程序执行结果
时间: 2024-08-05 19:37:05