AAA_Dev
AAA_Dev

Reputation: 23

PHP IntlDateFormatter returns incorrect year

I have an issue with a date conversion and after a lot of tests I don't understand what I missed.
I start with a typical datetime stored in a MySQL database (2019-12-31 09:35:16).
To be more precise, I'm on Windows with PHP 7.2.10

Here's a simple example:

$formatter = new IntlDateFormatter(
    'fr-FR',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    new DateTimeZone('Europe/Paris'),
    IntlDateFormatter::GREGORIAN,
    'd/M/Y HH:mm \'UTC\'XXX'
);
echo $formatter->format(new \DateTime('2019-12-31 09:35:16'));

And the answer give me 31/12/2020 09:35 UTC+01:00 instead of 31/12/2019 09:35 UTC+01:00.
After some attempts, this change on year appears also for 2013 and 2025 (and probably happens every six years...).

What am I doing wrong?

Upvotes: 2

Views: 372

Answers (1)

aynber
aynber

Reputation: 23001

It's a difference in the formats. It doesn't use the PHP date formats, it uses the ICU date formats. The y/Y formats are different:

Date Field Symbol Table

Symbol  Meaning                   Example(s)
y       year                      (yy or y or yyyy) 96 or 1996
Y       year of "Week of Year"    Y   1997

Since 2019-12-31 is on a Tuesday, it belongs to the week year of 2020. Instead, you'd use y for the format.

$formatter = new IntlDateFormatter(
    'fr-FR',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    new DateTimeZone('Europe/Paris'),
    IntlDateFormatter::GREGORIAN,
    'd/M/y HH:mm \'UTC\'XXX'
);
echo $formatter->format(new \DateTime('2019-12-31 09:35:16'));

Upvotes: 1

Related Questions