Calculate previous week's start and end date

前端 未结 7 1681
甜味超标
甜味超标 2020-12-13 17:41

What is the best way to calculate the previous week\'s start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last we

7条回答
  •  遥遥无期
    2020-12-13 18:18

    Current accepted answer will fail for Sundays by giving the Monday of the current week instead of last weeks Monday. (code with unit tests output)

    DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
    //Failed to get start of last-week from date-time: 2020-03-01T00:00:00.0000000Z
    //  Expected: 2020-02-17 00:00:00.000
    //  But was:  2020-02-24 00:00:00.000
    

    The following bit of code addresses this issue:

    var dayOfWeek = (int) date.DayOfWeek - 1;
    if (dayOfWeek < 0) dayOfWeek = 6;
    
    var thisWeeksMonday = date.AddDays(-dayOfWeek).Date;
    var lasWeeksMonday = thisWeeksMonday.AddDays(-7);
    

    which can be reduced to a one-liner should you so desire (I do not recommend using this barely readable code...):

    var mondayOfLastWeek  = date.AddDays(-(7 + ((int)date.DayOfWeek - 1 == -1 ? 6 : (int)date.DayOfWeek - 1)));
    

提交回复
热议问题