Question

Given a week-day (1-7), how can I calculate what that week-day's last date was?

Example: Today is Wednesday, 2008/11/12, and I want to know what last Friday's date was.

Was it helpful?

Solution

If today is the current day of the week, then you can use something like:

days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7

This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract days_since_friday from the current date, and you'll get the date of the end of last week.

The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:

days_since_friday = ((today + 7) - 5) % 7

or

days_since_friday = (today + 2) % 7

OTHER TIPS

In general? See Calendrical Calculations.

In this narrower case of within the previous week? Find the difference in days (Friday = 5, Wednesday = 3). Find differences in weeks (last week = -7 days). When you've found the offset in days+weeks, apply that offset to the calendar date.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top