phparraysdatefrench

display a date in particular format from month array in php


I have a php code as shown below in which there is an array of french months.

<?php
$months = array(
    1 => "janvier",
    2 => "février",
    3 => "mars",
    4 => "avril",
    5 => "mai",
    6 => "juin",
    7 => "juillet",
    8 => "août",
    9 => "septembre",
    10 => "octobre",
    11 => "novembre",
    12 => "décembre",
);
?>

Problem Statement:

What I want to achieve is I want to display a date in the following format:

08 août 2020

For the first day of the month, append er to the number:

e.g. 1er août 2020

This is what I have tried. Although it's working as Line A prints 08 août 2020 but I am wondering if its gonna work in all cases. All cases here means for all days of the month.

I have hardcoded the value at Line Z but it will change.

<?php
$months = array(
    1 => "janvier",
    2 => "février",
    3 => "mars",
    4 => "avril",
    5 => "mai",
    6 => "juin",
    7 => "juillet",
    8 => "août",
    9 => "septembre",
    10 => "octobre",
    11 => "novembre",
    12 => "décembre",
);
$this_date="2020-08-08";   // Line Z 
$this_time = strtotime($this_date);
$day = date('d', $this_time);
$month = date('n', $this_time);
$month_fr = $months[$month];
$suffix = $day == 1 ? 'er' : '';
$formatted_new_fr = strftime("%d$suffix " . $month_fr . " %Y", $this_time);
echo $formatted_new_fr;  // Line A
?>

Solution

  • PHP got you covered :)

    setlocale(LC_TIME, 'fr_FR');
    
    $dateString = '2020-08-08';
    $timestamp = strtotime($dateString);
    $formattedDate = strftime('%d %B %Y', $timestamp);
    //setlocale(LC_ALL, Locale::getDefault()); // restore (if neccessary)
    
    echo utf8_encode($formattedDate);
    

    output

    08 août 2020
    

    Working example.

    To get the 1er day you can do what you already did. Just split up the strftime(or its result).

    references


    another solution (will display all days ordinally though)

    $locale = 'fr_FR';
    $dateString = '2020-08-01';
    $date = new DateTimeImmutable($dateString);
    $dateFormatter = new IntlDateFormatter(
        $locale,
        IntlDateFormatter::FULL,
        NULL
    );
    
    $numberFormatter = new NumberFormatter($locale, NumberFormatter::ORDINAL);
    $ordinalDay = $numberFormatter->format($date->format('d'));
    $dateFormatter->setPattern('LLLL Y');
    
    echo $ordinalDay . ' ' . $dateFormatter->format($date->getTimestamp());
    

    output

    1er août 2020
    

    Working example.

    references