Calculate previous week's start and end date

前端 未结 7 1664
甜味超标
甜味超标 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:25

    DayOfWeek weekStart = DayOfWeek.Monday; // or Sunday, or whenever
    DateTime startingDate = DateTime.Today;
    
    while(startingDate.DayOfWeek != weekStart)
        startingDate = startingDate.AddDays(-1);
    
    DateTime previousWeekStart = startingDate.AddDays(-7);
    DateTime previousWeekEnd = startingDate.AddDays(-1);
    

    Read: Backtrack one day at a time until we're at the start of this week, and then subtract seven to get to the start of last week.

提交回复
热议问题