How can I get the DateTime for the start of the week?

前端 未结 30 2739
走了就别回头了
走了就别回头了 2020-11-22 12:57

How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?

Something like:

DateTime.Now.StartWeek(Monday);
         


        
30条回答
  •  再見小時候
    2020-11-22 13:19

    Calculating this way lets you choose which day of the week indicates the start of a new week (in the example I chose Monday).

    Note that doing this calculation for a day that is a Monday will give the current Monday and not the previous one.

    //Replace with whatever input date you want
    DateTime inputDate = DateTime.Now;
    
    //For this example, weeks start on Monday
    int startOfWeek = (int)DayOfWeek.Monday;
    
    //Calculate the number of days it has been since the start of the week
    int daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;
    
    DateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);
    

提交回复
热议问题