Finding Dates for Weekdays of Other Weeks
Problem
You want to compute the date for some weekday of some other week.
Solution
Figure out the date for that weekday in the current week, then shift the result into the desired week.
Discussion
Calculating the date for a day of the week in some other week is a
problem that breaks down into a day-within-week shift (using the
formula given in the previous section) plus a week shift. These
operations can be done in either order because the amount of shift
within the week is the same whether or not you shift the reference
date into a different week first. For example, to calculate Wednesday
of a week by the preceding formula, n is
4. To compute the date for Wednesday two weeks ago, you can perform
the day-within-week shift first, like this:
mysql>SET @target =->DATE_SUB(DATE_ADD(CURDATE( ),INTERVAL 4-DAYOFWEEK(CURDATE( )) DAY),->INTERVAL 14 DAY);mysql>SELECT CURDATE( ), @target, DAYNAME(@target);+------------+------------+------------------+ | CURDATE( ) | @target | DAYNAME(@target) | +------------+------------+------------------+ | 2002-07-15 | 2002-07-03 | Wednesday | +------------+------------+------------------+
Or you can perform the week shift first:
mysql>SET @target =->DATE_ADD(DATE_SUB(CURDATE( ),INTERVAL 14 DAY),->INTERVAL 4-DAYOFWEEK(CURDATE( )) DAY);mysql>SELECT CURDATE( ), @target, DAYNAME(@target);+------------+------------+------------------+ | CURDATE( ) | @target | DAYNAME(@target) | +------------+------------+------------------+ ...