Code
/// <summary> /// 计算 指定年第几周,加减N周后时间范围 /// </summary> /// <param name="year">指定年</param> /// <param name="week">第几周</param> /// <param name="weekDiffNum">加减N周</param> [Theory] [InlineData(2022, 2, -2)] [InlineData(2023, 2, -2)] [InlineData(2023, 3, 1)] [InlineData(2023, 4, -2)] public void CalcWeekDiff(int year, int week, int weekDiffNum) { // 今年第一天 var firstDay = new DateTime(year, 1, 1); // 今年第一周的最后一天 = 6(礼拜天是0,礼拜六是6) - 当前天是本周第几天 var firstWeekLastDay = firstDay.AddDays(6 - (int)firstDay.DayOfWeek); TestOutputHelper.WriteLine($"year:{year}\t第一天:{firstDay.ToShortString()}\t在第一周中属于第几天:{(int)firstDay.DayOfWeek}\tRange:[{firstWeekLastDay.AddDays(-6).ToShortString()} => {firstWeekLastDay.ToShortString()}]"); // 得到指定周最后一天 var specifyDate = firstWeekLastDay.AddDays((week - 1) * 7); TestOutputHelper.WriteLine($"第[{week}]周\tRange:[{specifyDate.AddDays(-6).ToShortString()} => {specifyDate.ToShortString()}]"); // 计算指定周后的范围 var calcDiffDate = specifyDate.AddDays(weekDiffNum * 7); TestOutputHelper.WriteLine($"操作[{weekDiffNum}]周\tRange:[{calcDiffDate.AddDays(-6).ToShortString()} => {calcDiffDate.ToShortString()}]"); }
Result
year:2022 第一天:2022-01-01 在第一周中属于第几天:6 Range:[2021-12-26 => 2022-01-01] 第[2]周 Range:[2022-01-02 => 2022-01-08] 操作[-2]周 Range:[2021-12-19 => 2021-12-25]
标签:01,C#,AddDays,加减,int,周后,2022,year,ToShortString From: https://www.cnblogs.com/CRobot/p/17319013.html