skip to Main Content

I have this simple code, which used to work correctly before:

<?php
$dateFormatted = MessageFormatter::formatMessage(
    'en_US', "{0, date, d MMMM YYYY}", [new DateTime()]
);

var_dump($dateFormatted); // 28 December 2019

But from Dec 29th, 2019 it shows next year’s date:

var_dump($dateFormatted); // 29 December 2020

And this happens for every year I checked until 2050. As far as I know, it only happens on last december days, but I’m not sure. 2018 year unaffected. Why this happens and is there any fix to it?

php version 7.1

Upd: looks like strftime has same problem

Upd2: strftime show correct year with %Y but not with %G

2

Answers


  1. Unfortinatly the documention of MessageFormatter is not explain about date formating. but i found how to fix it. you can use lower y. try:

    $dateFormatted = MessageFormatter::formatMessage(
        'en_US', "{0, date, d MMMM y}", [new DateTime()]
    );
    echo $dateFormatted; // 30 December 2019
    

    And for strftime you can use strftime("%d %B %Y").
    I think this issue come from the ISO_8601 standard of format

    Login or Signup to reply.
  2. Uppper case Y means year of “Week of Year” (reference), according to ISO-8601:1988 week number definition in which the last days of calendar year typically belong to the first week of next year. You want lower case y:

    <?php
    $dateFormatted = MessageFormatter::formatMessage(
        'en_US', "{0, date, d MMMM YYYY} / {0, date, d MMMM yyyy}", [new DateTime('2019-12-29')]
    );
    var_dump($dateFormatted);
    
    string(37) " 29 December 2020 /  29 December 2019"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search