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

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

    Thanks for the examples. I needed to always use the "CurrentCulture" first day of the week and for an array I needed to know the exact Daynumber.. so here are my first extensions:

    public static class DateTimeExtensions
    {
        //http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
        //http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1
        public static DateTime StartOfWeek(this DateTime dt)
        {
            //difference in days
            int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.
    
            //As a result we need to have day 0,1,2,3,4,5,6 
            if (diff < 0)
            {
                diff += 7;
            }
            return dt.AddDays(-1 * diff).Date;
        }
    
        public static int DayNoOfWeek(this DateTime dt)
        {
            //difference in days
            int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.
    
            //As a result we need to have day 0,1,2,3,4,5,6 
            if (diff < 0)
            {
                diff += 7;
            }
            return diff + 1; //Make it 1..7
        }
    }
    

提交回复
热议问题