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

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

    Putting it all together, with Globalization and allowing for specifying the first day of the week as part of the call we have

    public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )
    {
        DayOfWeek fdow;
    
        if ( firstDayOfWeek.HasValue  )
        {
            fdow = firstDayOfWeek.Value;
        }
        else
        {
            System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            fdow = ci.DateTimeFormat.FirstDayOfWeek;
        }
    
        int diff = dt.DayOfWeek - fdow;
    
        if ( diff < 0 )
        {
            diff += 7;
        }
    
        return dt.AddDays( -1 * diff ).Date;
    
    }
    

提交回复
热议问题