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

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

    Modulo in C# works bad for -1mod7 (should be 6, c# returns -1) so... "oneliner" solution to this will look like this :)

    private static DateTime GetFirstDayOfWeek(DateTime date)
        {
            return date.AddDays(-(((int)date.DayOfWeek - 1) - (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
        }
    

提交回复
热议问题