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

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

    try with this in c#.With this code you can get both first date and last date of a given week.Here Sunday is the first day and Saturday is the last day but you can set both day's according to your culture

    DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date,DayOfWeek.Sunday);
    DateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);
    
    public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
    {
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);
    
        return firstDayInWeek;
    }
    public static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
    {
        DateTime lastDayInWeek = dayInWeek.Date;
        while (lastDayInWeek.DayOfWeek != firstDay)
            lastDayInWeek = lastDayInWeek.AddDays(1);
    
        return lastDayInWeek;
    }
    
    0 讨论(0)
  • 2020-11-22 13:28

    The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:

    private DateTime getStartOfWeek(bool useSunday)
    {
        DateTime now = DateTime.Now;
        int dayOfWeek = (int)now.DayOfWeek;
    
        if(!useSunday)
            dayOfWeek--;
    
        if(dayOfWeek < 0)
        {// day of week is Sunday and we want to use Monday as the start of the week
        // Sunday is now the seventh day of the week
            dayOfWeek = 6;
        }
    
        return now.AddDays(-1 * (double)dayOfWeek);
    }
    
    0 讨论(0)
  • 2020-11-22 13:28

    Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week.

        DateTime WeekBeginning(DateTime input)
        {
            do
            {
                if (input.DayOfWeek.ToString() == "Monday")
                    return input;
                else
                    return WeekBeginning(input.AddDays(-1));
            } while (input.DayOfWeek.ToString() == "Monday");
        }
    
    0 讨论(0)
  • 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.

    /// <summary>
    /// Gets the date of the first day of the week for the date.
    /// </summary>
    /// <param name="date">The date to be used</param>
    /// <param name="cultureInfo">If none is provided, the current culture is used</param>
    /// <returns>The date of the beggining of the week based on the culture specifed</returns>
    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()}");
            }
        }
    
    0 讨论(0)
  • 2020-11-22 13:30

    This would give you the preceding Sunday (I think):

    DateTime t = DateTime.Now;
    t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);
    
    0 讨论(0)
  • 2020-11-22 13:31

    Using Fluent DateTime:

    var monday = DateTime.Now.Previous(DayOfWeek.Monday);
    var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);
    
    0 讨论(0)
提交回复
热议问题