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

前端 未结 30 2209
走了就别回头了
走了就别回头了 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;
    }
    

提交回复
热议问题