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

370 views Asked by At

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

There are 1 answers

1
shalvah On

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.