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

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

    You could use the excellent Umbrella library:

    using nVentive.Umbrella.Extensions.Calendar;
    DateTime beginning = DateTime.Now.BeginningOfWeek();
    

    However, they do seem to have stored Monday as the first day of the week (see the property nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn), so that previous localized solution is a bit better. Unfortunate.

    Edit: looking closer at the question, it looks like Umbrella might actually work for that too:

    // Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
    DateTime monday = DateTime.Now.PreviousMonday(); 
    DateTime sunday = DateTime.Now.PreviousSunday();
    

    Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use BeginningOfWeek, which seems like a bug :(.

提交回复
热议问题