问题
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
回答1:
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 has at least 4 days in the new year (so it's the week containing the new year's first 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 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
回答2:
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.
回答3:
YEARWEEK takes a second (optional) parameter that specifies the range of the week [0- 53] or [1-53]).
This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used.
while date(W)
is an ISO8601 date that is always in the range [01-53]. Therefore my guess is that by default YEARWEEK is using the [0-53] range.
So, if you want to get the same result try using 1 as the second parameter for YEARWEEK
来源:https://stackoverflow.com/questions/15562270/php-datew-vs-mysql-yearweeknow