PHP date('W') vs MySQL YEARWEEK(now())

Prasad Rajapaksha picture Prasad Rajapaksha · Mar 22, 2013 · Viewed 10.1k times · Source

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

Answer

Mark Reed picture Mark Reed · Mar 22, 2013

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