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

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

    Here is a combination of a few of the answers. It uses an extension method that allows the culture to be passed in, if one is not passed in, the current culture is used. This will give it max flexibility and re-use.

    /// 
    /// Gets the date of the first day of the week for the date.
    /// 
    /// The date to be used
    /// If none is provided, the current culture is used
    /// The date of the beggining of the week based on the culture specifed
    public static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>         
                 date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo??CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;
    

    Example Usage:

    public static void TestFirstDayOfWeekExtension() {          
            DateTime date = DateTime.Now;
            foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {
                Console.WriteLine($"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}");
            }
        }
    

提交回复
热议问题