Can someone kindly explain me why these two give different results?
I execute this with PHP.
date("YW",mktime(0, 0, 0, 3, 22 , 2013)); // outputs 201312
And when I execute this with MySQL
SELECT YEARWEEK(now()); // outputs 201311
MySQL YEARWEEK() Function The YEARWEEK() function returns the year and week number (a number from 0 to 53) for a given date.
You need to specify mode 3 on the mysql YEARWEEK call:
SELECT YEARWEEK(now(),3);
The PHP date()
placeholder W
returns the week number according to the ISO 8601 specification. That means weeks start on Monday (not Sunday), the first week of the year is number 1 (not 0), and that week is the first one that with more than half its days in the new year (so it has to be January by Thursday). According to the documentation for the MySQL WEEK function, that combination of options is mode 3.
Also, to pull Alles's note into the accepted answer because it's important: the placeholders Y
and W
don't go together. If you want the year that goes with the ISO week number, you should use o
instead of Y
. For example, consider the week starting on Monday, December 29th, 2014:
date('YW', mktime(0,0,0,12,29,2014)); #=> 201401 : 1st week of 2014??
date('oW', mktime(0,0,0,12,29,2014)); #=> 201501 : better
Please be aware that YEARWEEK('2012-01-01', 3) => 201152 while the PHP "YW" will give 201252. The year in the result may be different from the year in the date argument for the first and the last week of the year. (i.e. the year in the YEARWEEK is the year of the Monday of the week and not the year of the date being used to calculate).
In order to get the right result, you need to do
date("oW",mktime(0, 0, 0, 1, 1, 2012)); // outputs 201152
as "o" gives you the Year the week belongs to.
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With