IntlDateFormatter::format adds a year to a date

696 views Asked by At

This is weird, perhaps even a bug...

The timestamp for Dec 26, 2021 00:00:00 GMT is 1640476800:

php > var_dump(gmdate("Y-m-d H:i:s", 1640476800));
string(19) "2021-12-26 00:00:00"

But when I use IntlDateFormatter::format(), the year changes to 2022

php > $idf = new IntlDateFormatter(
    locale: null, 
    dateType: IntlDateFormatter::FULL, 
    timeType: IntlDateFormatter::FULL, 
    pattern: 'YYYY MM d'
);
$idf->setTimeZone("GMT");
var_dump($idf->format(1640476800));
string(10) "2022 12 26"

Dates before Dec 26 works fine. Am I missing something? Tested on PHP 7.4, 8.0.13 and 8.1.1, and in my default timezone (GMT -5)

1

There are 1 answers

0
drmad On BEST ANSWER

Thanks StackOverflow for helping me rubberduck-debugged this thing.

'Y' in ISO date format is used to specify a "Week Year", a very confusing week-based year, which is very similar to a 'calendar' year, except sometimes at the beginning or end of it.

To specify a 'calendar' year, the term is 'y' (lowercase). So the pattern YYYY MM d must actually be yyyy MM d.