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

前端 未结 30 2550
走了就别回头了
走了就别回头了 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条回答
  •  旧时难觅i
    2020-11-22 13:18

    Following on from Compile This' Answer, use the following method to obtain the date for any day of the week:

    public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)
    {
       var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);
    
       var diff = dayOfWeek - DayOfWeek.Monday;
    
       if (diff == -1)
       {
          diff = 6;
       }
    
       return monday.AddDays(diff);
    } 
    

提交回复
热议问题