Why does strftime('%G', strtotime('2017-01-01')) produce 2016?

北城余情 提交于 2019-12-11 04:01:52

问题


I found a possible bug in PHP 5.6. The function strftime with a parameter of %G generates the 4 digit year. However, it seems to return the wrong year when fed 1483246800 - i.e. Jan 1, 2017. It returns 2016 instead!

Example code snippet:

echo strftime('%G', strtotime('2017-01-01'));

This should print "2017", but I get "2016" instead. I am running PHP 5.6. This edge case also shows up for other years - e.g. 2016-01-03 outputs 2015 instead of 2016.


回答1:


It's not a bug.

As someone pointed out in answer to a bug report someone else filed a while back:

%G - The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead...A reminder about ISO week numbers. They begin on mondays, end on sundays, and are considered a part of the year in which the majority of their days fall.

This means that using %G for a date close to a year's beginning/end could give you the correct year, the previous year, as in your case, or the next year, (for example, echo strftime('%Y', strtotime('2002-12-30)) gives 2003).

If you want to get the correct year, you should use %Y instead. echo strftime('%Y', strtotime('2017-01-01')); gives 2017.

It's also worth checking out the definition of %V:

ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week.



来源:https://stackoverflow.com/questions/41513143/why-does-strftimeg-strtotime2017-01-01-produce-2016

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!