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

前端 未结 30 2776
走了就别回头了
走了就别回头了 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:33

    Tried several but did not solve the issue with a week starting on a Monday, resulting in giving me the coming Monday on a Sunday. So I modified it a bit and got it working with this code:

    int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
    DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
    return monday;
    

提交回复
热议问题