Week Ending Date has been requested a lot more frequently now. It's an odd one but the example below shows how to do this for when the week ends on Friday. Assuming it starts on the previous Saturday.
Why?
Problems with MySQL weeks always starting on Sunday means this isn't very useful. I have another system which starts on Monday and ends on the following Sunday. The solution below is for the opposite, where the week starts on the previous Saturday and ends on the last working day of the week.
The Solution
Where "givenDate" is the given date you have to calculate the last working day of:
-- SAMPLE DATES ARE: -- -- 2012-04-27 10:00:00 -- is a Friday -- 2012-04-28 11:00:00 -- is a Saturday -- 2012-04-29 12:00:00 -- is a Sunday DATE_ADD( givenDate, INTERVAL ( 6 - DATE_FORMAT( DATE_ADD(givenDate, INTERVAL 1 DAY), \'%w\' ) ) DAY ) AS WeDate -- OR -- DATE_ADD( givenDate, INTERVAL ( 7 - DAYOFWEEK( DATE_ADD(givenDate, INTERVAL 1 DAY) ) ) DAY ) AS WeDate -- yields -- 2012-04-27 -- this Friday -- 2012-05-04 -- next Friday -- 2012-05-04 -- next Friday
- -- SAMPLE DATES ARE: --
- -- 2012-04-27 10:00:00 -- is a Friday
- -- 2012-04-28 11:00:00 -- is a Saturday
- -- 2012-04-29 12:00:00 -- is a Sunday
- DATE_ADD(
- givenDate,
- INTERVAL (
- 6 - DATE_FORMAT(
- DATE_ADD(givenDate, INTERVAL 1 DAY), \'%w\'
- )
- ) DAY
- ) AS WeDate
- -- OR --
- DATE_ADD(
- givenDate,
- INTERVAL (
- 7 - DAYOFWEEK(
- DATE_ADD(givenDate, INTERVAL 1 DAY)
- )
- ) DAY
- ) AS WeDate
- -- yields
- -- 2012-04-27 -- this Friday
- -- 2012-05-04 -- next Friday
- -- 2012-05-04 -- next Friday
If you were starting on Monday
...So if your week ends on a Sunday
-- SAMPLE DATES ARE: -- -- 2012-04-27 10:00:00 -- is a Friday -- 2012-04-28 11:00:00 -- is a Saturday -- 2012-04-29 12:00:00 -- is a Sunday DATE_ADD( givenDate, INTERVAL ( 6 - weekday(givenDate) ) DAY ) AS WeDate -- yields -- 2012-04-29 -- this Sunday -- 2012-04-29 -- this Sunday -- 2012-04-29 -- this Sunday
- -- SAMPLE DATES ARE: --
- -- 2012-04-27 10:00:00 -- is a Friday
- -- 2012-04-28 11:00:00 -- is a Saturday
- -- 2012-04-29 12:00:00 -- is a Sunday
- DATE_ADD(
- givenDate,
- INTERVAL (
- 6 - weekday(givenDate)
- ) DAY
- ) AS WeDate
- -- yields
- -- 2012-04-29 -- this Sunday
- -- 2012-04-29 -- this Sunday
- -- 2012-04-29 -- this Sunday
Other Searches
- These didn't get me very far until I decided to write this article:
- DAYOFWEEK(myDate, 1) or WEEKDAY(mydate, 1)
- MySQL code for first and last day of week.
- Day of Week starting on Monday.