find week ending date of last completed week

后端 未结 5 920
独厮守ぢ
独厮守ぢ 2021-01-04 07:04

For any given date, how would you find the week ending date of the last completed week, if your week runs from Sunday to Saturday?

相关标签:
5条回答
  • 2021-01-04 07:47
    DateTime givenDate; // = ...
    int daysToOffset = ((int)givenDate.DayOfWeek + 1) * -1;
    DateTime lastDayOfLastCompletedWeek = givenDate.AddDays(daysToOffset);
    
    0 讨论(0)
  • 2021-01-04 07:48
    DateTime StartOfWeek = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
    DateTime EndOfLastWeek = StartOfWeek.AddDays(-1);
    
    0 讨论(0)
  • 2021-01-04 07:48
        public static DateTime EndOfWeek(DateTime dateTime)
        {
            DateTime start = StartOfWeek(dateTime);
    
            return start.AddDays(6);
        }
    
        public static DateTime StartOfWeek(DateTime dateTime)
        {
            int days = dateTime.DayOfWeek - DayOfWeek.Monday; 
    
            if (days < 0) 
                days += 7;
    
            return dateTime.AddDays(-1 * days).Date;
        }
    

    To find the end of the previous week, just call:

        DateTime endPrevWeek = StartOfWeek(DateTime.Today).AddDays(-1);
    
    0 讨论(0)
  • 2021-01-04 07:54

    If you want to specify which day is the end of week, and you don't want to worry about what day the system has defined as the default start of the week, use this method:

    private static DateTime GetPreviousSpecifiedDayOfWeek(DateTime dt, DayOfWeek day)
        {
            if (dt.DayOfWeek == day)
            {
                return dt;
            }
    
            while (dt.DayOfWeek != day)
            {
                dt = dt.AddDays(-1);
            }
    
            return dt;
        }
    
    0 讨论(0)
  • 2021-01-04 07:57

    .NET DateTimes expose a DayOfWeek property. You can leverage that in this case:

    var currDay = DateTime.Today.DayOfWeek;
    //currday is now an enumeration with Sunday=0, Saturday=6
    //We can cast that to a number and subtract to get to the previous Saturday
    var EndOfLastWeek = DateTime.Today.AddDays(((int)currDay+1)*-1);
    
    0 讨论(0)
提交回复
热议问题