I need to calculate the number of the week following a given week. This is trivial for most weeks within the year, but not at the end / beginning of the year. For example if I need to know the week following week 52 of 2013.
I would like to use the defaul_week_format 3, i.e.
a) the weeks start with Monday (instead of Sunday)
b) the numbering within a year starts with 1 (instead of 0)
and c) week number 1 is the first week with more than 3 days this year.
My approach to e.g. calculate the week after week 36 2014 is the following:
SELECT WEEK(DATE_ADD(STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W'), INTERVAL 1 WEEK))
For this example I calculate the date of Tuesday in week 36, add one week, and calculate the week of this day. This would work, but even without adding one week, I have this strange behaviour:
It works for the default_week_format 0:
SET @@local.default_week_format=0;
SELECT STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W');
-> Tuesday of week 36 is 2014-09-09
SELECT week('2014-09-09');
-> 2014-09-09 is in week 36
So far, so good: Tuesday of week 36 is in week 36.
But this simple experiment does NOT work for default_week_format 3:
SET @@local.default_week_format=3;
SELECT STR_TO_DATE('W36 2014 Tuesday', 'W%V %X %W');
-> Tuesday of week 36 is 2014-09-09
-> This is wrong, because numbering should start with 1 (instead of 0 now)!
-> Tuesday of week 36 should be 2014-09-02
SELECT week('2014-09-09');
-> 2014-09-09 is in week 37
So MySQL tells me that Tuesday of week 36 is in week 37!
My only explanation for this:
- week() takes default_week_format into account
- str_to_date() ignores the default_week_format
How can I force MySQL function str_to_date to use the default_week_format?
Or: How else can I calculate the number of the following week?
I could also do it in PHP, but I get the weeks' numbers from a MySQL database.
Thanks for any help!