代码:
using System;
using System.Globalization;
using System.Collections.Generic;
class Program
{public static void Main(string[] args){var result = GetDateByYearWeek(2025,1);foreach(var item in result){Console.WriteLine(item.ToString("yyyy-MM-dd"));}}public static List<DateTime> GetDateByYearWeek(int year, int week){List<DateTime> dates = new List<DateTime>();DateTime first = DateTime.MinValue;DateTime last = DateTime.MinValue;var weekNum = week;if (year < 1700 || year > 9999){//"年份超限"return dates;}if (week < 1 || week > 53){//"周数错误"return dates;}DateTime startDay = new DateTime(year, 1, 1); //该年第一天int dayOfWeek = 0;if (Convert.ToInt32(startDay.DayOfWeek.ToString("d")) > 0)dayOfWeek = Convert.ToInt32(startDay.DayOfWeek.ToString("d")); //该年第一天为星期几if (dayOfWeek == 0) { dayOfWeek = 7; }week--;if (week == 1 && weekNum != 2){first = startDay.AddDays(7 - dayOfWeek - 6);if (dayOfWeek == 6){last = first;}else{last = startDay.AddDays((7 - dayOfWeek));}}else{first = startDay.AddDays((8 - dayOfWeek) + (week - 1) * 7); //index周的起始日期last = first.AddDays(6);}for (var date = first; date <= last; date = date.AddDays(1)){//对跨年数据进行过滤,若不做此判断,本年度最后一周和次年的第一周的数据相同if (date.Year == year){dates.Add(date);}}return dates;}
}
效果:
- 2024年第52周
- 2024年第53周
- 2025年第1周
- 2025年第2周
- 取消过滤后的2024年第53周和2025年第1周