2

How should I get the Day and Month (i.e. Friday, August) with the corresponding locale (i.e. de_DE) in PHP?

Most examples use setlocale() and strftime(), the last one being deprecated as of PHP 8.1.0.

Brethlosze
  • 1,533
  • 1
  • 22
  • 41
  • Does this answer your question? [PHP date - get name of the months in local language](https://stackoverflow.com/questions/13845554/php-date-get-name-of-the-months-in-local-language) – kmoser Aug 27 '22 at 02:23
  • @kmoser Most of the answers in there are using `strftime`... – Brethlosze Aug 27 '22 at 02:35
  • [This answer uses `IntlDateFormatter`](https://stackoverflow.com/a/66378193/378779), not `strftime()`. – kmoser Aug 27 '22 at 02:38

1 Answers1

3

You are correct about strftime() being deprecated, and date() (being a part of DateTimeInterface) will not work with setlocale(). One thing that will work with it is IntlDateFormatter:

$fmt = new IntlDateFormatter('de_DE',
    IntlDateFormatter::FULL, 
    IntlDateFormatter::FULL
);

echo $fmt->format(time());

Will output:

Samstag, 27. August 2022 00:58:15 GMT

You can play around with the Predefined Constants to specify different formats for the DateType and TimeType. I used FULL for my example. Read more here.

You can also change the Pattern

$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo $fmt->format(time());

To output (for example):

20220427 01:04:51 GMT

griv
  • 2,098
  • 2
  • 12
  • 15
  • I realize the `IntlDateFormatter::FULL` can be replaced by `null` – Brethlosze Aug 27 '22 at 02:33
  • I've updated my answer, correcting the link to the Predefined Constants. Correct, passing in null will cause it to get your default locale defined in your php.ini file. See [here](https://www.php.net/manual/en/intl.configuration.php#ini.intl.default-locale). – griv Aug 27 '22 at 02:42