# Finding Dates for Days of the Current Week

5.26.1 Problem

You want to compute the date for some other day of the current week.

5.26.2 Solution

Figure out the number of days between the starting day and the desired day, and shift the date by that many days.

5.26.3 Discussion

This section and the next describe how to convert one date to another when the target date is specified in terms of days of the week. To solve such problems, you need to know day-of-week values. For example, if you want to know what date it is on Tuesday of this week, the calculation depends on what day of the week it is today. If today is Monday, you add a day to CURDATE( ), but if today is Wednesday, you subtract a day.

MySQL provides two functions that are useful here. DAYOFWEEK( ) treats Sunday as the first day of the week and returns 1 through 7 for Sunday through Saturday. WEEKDAY( ) treats Monday as the first day of the week and returns 0 through 6 for Monday through Sunday. (The examples shown here use DAYOFWEEK( ).) Another kind of day-of-week operation involves determining the name of the day. DAYNAME( ) can be used for that.

Calculations that determine one day of the week from another depend on the day you start from as well as the day you want to reach. I find it easiest to shift the reference date first to a known point relative to the beginning of the week, then shift forward:

• Shift the reference date back by its DAYOFWEEK( ) value, which always produces the date for the Saturday preceding the week.
• Add one day to the result to reach the Sunday date, two days to reach the Monday date, and so forth.

In SQL, these operations can be expressed as follows for a date d, where n is 1 through 7 to produce the dates for Sunday through Saturday:

`DATE_ADD(DATE_SUB(d,INTERVAL DAYOFWEEK(d) DAY),INTERVAL n DAY)`

That expression splits the "shift back to Saturday" and "shift forward" phases into separate operations, but because the intervals for both DATE_SUB( ) and DATE_ADD( ) are both in days, the expression can be simplified into a single DATE_ADD( ) call:

`DATE_ADD(d,INTERVAL n-DAYOFWEEK(d) DAY)`

If we apply this formula to our date_val table, using an n of 1 for Sunday and 7 for Saturday to find the first and last days of the week, we get this result:

```mysql> SELECT d, DAYNAME(d) AS day,
-> DATE_ADD(d,INTERVAL 1-DAYOFWEEK(d) DAY) AS Sunday,
-> DATE_ADD(d,INTERVAL 7-DAYOFWEEK(d) DAY) AS Saturday
-> FROM date_val;
+------------+----------+------------+------------+
| d | day | Sunday | Saturday |
+------------+----------+------------+------------+
| 1864-02-28 | Sunday | 1864-02-28 | 1864-03-05 |
| 1900-01-15 | Monday | 1900-01-14 | 1900-01-20 |
| 1987-03-05 | Thursday | 1987-03-01 | 1987-03-07 |
| 1999-12-31 | Friday | 1999-12-26 | 2000-01-01 |
| 2000-06-04 | Sunday | 2000-06-04 | 2000-06-10 |
+------------+----------+------------+------------+```

MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois