views:

452

answers:

3

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.

A: 

Can't you just subtract x days? What language/library are you using?

Filip
Sybase's Transact-SQL.It does have a DATEADD function.DATEADD(DD, -1, GETDATE())
lamcro
I want to substract x days. But I don't know how to calculate x.
lamcro
+1  A: 

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
Greg Hewgill
is "today" the day of the week or the day of the month?
lamcro
"today" is today's day of the week.
Greg Hewgill
ok, I understand now. Thanks.
lamcro
+3  A: 

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.

S.Lott