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

后端 未结 3 2059
情深已故
情深已故 2021-01-01 23:04

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 2         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 23:42

    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
    

提交回复
热议问题