[ACCEPTED]-find week ending date of last completed week-.net

Accepted answer
Score: 21
DateTime StartOfWeek = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
DateTime EndOfLastWeek = StartOfWeek.AddDays(-1);

0

Score: 2
DateTime givenDate; // = ...
int daysToOffset = ((int)givenDate.DayOfWeek + 1) * -1;
DateTime lastDayOfLastCompletedWeek = givenDate.AddDays(daysToOffset);

0

Score: 2
    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 1 call:

    DateTime endPrevWeek = StartOfWeek(DateTime.Today).AddDays(-1);
Score: 1

.NET DateTimes expose a DayOfWeek property. You 1 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);
Score: 0

If you want to specify which day is the 4 end of week, and you don't want to worry 3 about what day the system has defined as 2 the default start of the week, use this 1 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;
    }
Score: 0

Here is a .NET method that does it generically:

public static DateTime GetPreviousDayDate(DateTime referenceDate, DayOfWeek day = DayOfWeek.Saturday)
{
    // DayOfWeek: https://docs.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-5.0
    // Sunday = 0, Monday = 1, ..., Saturday = 6
    // e.g. if today is Wednesday (3), we subtract 4 days to get to the prior Saturday (6)
    // because 3 - 6 = -3 + 7 = 4
    // e.g. if today is Saturday (6), we substract 3 days to get to the prior Wednesday (3)
    // because 6 - 3 = 3

    int DaysToSubtract = (int)referenceDate.DayOfWeek - (int)day;

    // If the number of days to subtract based on the ordinal of the day of the week is negative, add 7 days back
    if (DaysToSubtract < 1) DaysToSubtract += 7;

    return referenceDate.AddDays(DaysToSubtract * -1);
}

0

More Related questions