Dave
Dave

Reputation: 493

Given the DayOfWeek number, find the date of a day in the previous week

This is likely to be embarrassingly simple but I'm having a "can't do basic math" kind of day.

I have a system where we cut off orders depending on which day it is, so for example after 4pm Friday you can't order for the next Sunday, or after 2pm Tuesday you can't order for the next day. Knowing that I need to say ok I need a product on Sunday 4th May, when is the cutoff, and have it tell me it's Friday 2nd May.

So I have the following code which doesn't work correctly

int offset = (int)reqDate.DayOfWeek - thiscafeday.day_number;

DateTime cutoffDateTime = reqDate.AddDays(-offset);

where reqDate.DayOfWeek is the Sunday(0) and thiscafeday.day_number is the Friday(5). I need Friday's date. The cutoffDateTime value is correct if the cutoff is next day but the Sunday (being DayOfWeek 0) seems to mess everything up. I often seem to end up getting the correct day but the next week, not the previous (I guess that us due to the minus offset).

If someone has a simple method to get the date of a previous arbitrary day within the past week given a current date I'd be very grateful for the help.

I did also try variations on the

((7- (int)reqDate.DayOfWeek + thiscafeday.day_number) % 7)

but can't get that to work either.

Any help appreciated.

Upvotes: 1

Views: 367

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292345

You can use these extension methods:

public static class DateExtensions
{
    public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek)
    {
        int start = (int)from.DayOfWeek;
        int wanted = (int)dayOfWeek;
        if (wanted <= start)
            wanted += 7;
        return from.AddDays(wanted - start);
    }

    public static DateTime Previous(this DateTime from, DayOfWeek dayOfWeek)
    {
        int end = (int)from.DayOfWeek;
        int wanted = (int)dayOfWeek;
        if (wanted >= end)
            end += 7;
        return from.AddDays(wanted - end);
    }
}


var lastFriday = DateTime.Today.Previous(DayOfWeek.Friday);

(it might need some adaptations for your specific scenario)

Upvotes: 2

Tim S.
Tim S.

Reputation: 56536

Instead of trying to calculate the days to offset by, you could simply step backwards until you're where you want to be.

DateTime GetDay(DateTime startDate, DayOfWeek targetDay)
{
    var date = startDate;
    while (date.DayOfWeek != targetDay)
    {
        date = date.AddDays(-1);
    }
    return date;
}

If you also require the offset, you can subtract the dates afterward:

DateTime startDate = new DateTime(2014, 4, 27); // Sunday
DateTime friday = GetDay(startDate, DayOfWeek.Friday);
int diff = (startDate - friday).Days; // subtracting DateTimes gives a TimeSpan
Console.WriteLine(diff); // 2

Upvotes: 1

Related Questions