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

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

    Step 1: Create a static class

      public static class TIMEE
    {
        public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
            return dt.AddDays(-1 * diff).Date;
        }
        public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = (7 - (dt.DayOfWeek - startOfWeek)) % 7;
            return dt.AddDays(1 * diff).Date;
        }
    }
    

    Step2: Use this class to get both start and end day of the week

     DateTime dt =TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
            DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);
    

提交回复
热议问题