2

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
?>
user1950349
  • 4,738
  • 19
  • 67
  • 119
  • I was about to post some tips, but they're more code review than anything else. I think this question doesn't fit this site as it doesn't actually specify a problem (your code works, as far as you know); maybe it could be posted on https://codereview.stackexchange.com instead? (Be sure to read their help pages first.) – IMSoP Aug 08 '20 at 17:05
  • @xNoJustice What does timezone have to do with month names? Are you confusing it with "locale"? – IMSoP Aug 08 '20 at 17:06

1 Answers1

1

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

SirPilan
  • 4,649
  • 2
  • 13
  • 26