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

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

    using System;
    using System.Globalization;
    
    namespace MySpace
    {
        public static class DateTimeExtention
        {
            // ToDo: Need to provide culturaly neutral versions.
    
            public static DateTime GetStartOfWeek(this DateTime dt)
            {
                DateTime ndt = dt.Subtract(TimeSpan.FromDays((int)dt.DayOfWeek));
                return new DateTime(ndt.Year, ndt.Month, ndt.Day, 0, 0, 0, 0);
            }
    
            public static DateTime GetEndOfWeek(this DateTime dt)
            {
                DateTime ndt = dt.GetStartOfWeek().AddDays(6);
                return new DateTime(ndt.Year, ndt.Month, ndt.Day, 23, 59, 59, 999);
            }
    
            public static DateTime GetStartOfWeek(this DateTime dt, int year, int week)
            {
                DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
                return dayInWeek.GetStartOfWeek();
            }
    
            public static DateTime GetEndOfWeek(this DateTime dt, int year, int week)
            {
                DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
                return dayInWeek.GetEndOfWeek();
            }
        }
    }
    

提交回复
热议问题