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

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

    Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week.

        DateTime WeekBeginning(DateTime input)
        {
            do
            {
                if (input.DayOfWeek.ToString() == "Monday")
                    return input;
                else
                    return WeekBeginning(input.AddDays(-1));
            } while (input.DayOfWeek.ToString() == "Monday");
        }
    

提交回复
热议问题