Richard Reddy
Richard Reddy

Reputation: 2170

How to get previous date using DayOfWeek?

I have a reminder table in my database that has 2 columns to store the ActionDay and ReminderDay. These days are both stored as integers: 0 (sun) -> 6 (sat) to represent the days of the week.

When I load my page I'd like to show the next ActionDay date and along with the ReminderDay date.

I can work out the next ActionDay date using this:

public static class DateTimeExtensions
{
    public static DateTime Next(this DateTime date, DayOfWeek weekday)
    {
        return (from i in Enumerable.Range(0, 7)
                where date.AddDays(i).DayOfWeek == weekday
                select date.AddDays(i)).First();

    }
}

I'm having some trouble working out the previous date from the ActionDay.

For example, (using today's date of 26 Oct 2011): If the ActionDay is '3' and the ReminderDay is '2' then I expect 'Wed, 26 Oct' for the ActionDay and 'Tues, 25 Oct' for the ReminderDay.

If the ActionDay is 0 and the ReminderDay is 6 I'd expect 'Sun, 30 Oct' and 'Sat, 29 Oct'

Any suggestions on how I might be able to get this Reminder date? I'd also be interested to know if there are any good c# datetime extensions/snippets as it might be easier to plug in something that someone else has tested than writing my own here :)

Thanks, Rich

Upvotes: 2

Views: 777

Answers (1)

Andrei
Andrei

Reputation: 56688

You can calculate the difference between the ActionDay and ReminderDay and then call the AddDay() function on the DateTime representing the action day to get the DateTime for reminder day:

// here a stands for the number representing the action day, and r for the reminder day
// a and r are both integers from 0 to 6
int diff;
if (a >= r)
{
    diff = a - r;
}
else
{
    diff = a + 7 - r;
}

DateTime reminderDateTime = actionDateTime.AddDays(-1 * diff);

Upvotes: 3

Related Questions