Home > Software engineering >  Date format return wrong year in PHP with DateFmt in French
Date format return wrong year in PHP with DateFmt in French

Time:03-09

I wrote this function

function formatted_month($month) {
    $first_day_in_month = new DateTime('2022-01-01');

    $fmt = datefmt_create(
        'en_EN',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Paris',
        IntlDateFormatter::GREGORIAN,
        'MMMM YY'
    );
    $formatted_month = datefmt_format($fmt,$first_day_in_month);

    return $formatted_month;
}

This return January 22 as expected but this code :

function formatted_month($month) {
    $first_day_in_month = new DateTime('2022-01-01');

    $fmt = datefmt_create(
        'fr_FR',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Paris',
        IntlDateFormatter::GREGORIAN,
        'MMMM YY'
    );
    $formatted_month = datefmt_format($fmt,$first_day_in_month);

    return $formatted_month;
}

Return janvier 21. The only difference is this line

'en_EN', -> 'fr_FR'

Same thing for es_ES and non English languages...

Do you have any explanation ? Thanks

CodePudding user response:

This is a subtle mistake of the formatting string, which is that there are multiple different year specifiers:

  • A lower-case yy or yyyy is the normal year you would expect, for use with month and day
  • An upper-case YY or YYYY is the year for use with "week of year"

For the majority of dates, these are the same, so the difference is easy to overlook. But at the very beginning and end of the year, it matters where the week begins and ends - January 1st may still be in the last week of the previous year, or December 31st may be in the first week of the next year.

We can see the difference clearly if we use a format string of 'ww YYYY, MMMM yyyy', to show the week number and both definitions of year:

  • For en_GB we get "01 2022, January 2022"
  • For fr_FR we get "52 2021, janvier 2022"

So always use the lower-case "yy" form, unless you are actually displaying week numbers.

CodePudding user response:

Solution given by @IMSoP works as expected Thank you!

function formatted_month($month) {
    $first_day_in_month = new DateTime($month.'-01');

    $fmt = datefmt_create(
        'fr_FR',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Paris',
        IntlDateFormatter::GREGORIAN,
        'MMMM yyyy'
    );

    $formatted_month = datefmt_format($fmt,$first_day_in_month);

    return ucfirst($formatted_month);
}
  • Related