Tuesday, March 1, 2011

Calculating date for a day of the week

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.

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

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

0 comments:

Post a Comment