Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 8.1: strftime() is deprecated

Tags:

php

When upgrading to PHP 8.1, I got an error regarding "strftime". How do I correct the code to correctly display the full month name in any language?

 $date = strftime("%e %B %Y", strtotime('2010-01-08'))
like image 306
novaidea Avatar asked Sep 03 '25 04:09

novaidea


2 Answers

To my dear and late strftime()... I found a way to adapt with IntlDateFormatter::formatObject and here is the link for the references to the schemas:

https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table

... For those who want to format the date more precisely

// "date_default_timezone_set" may be required by your server
date_default_timezone_set( 'Europe/Paris' );

// make a DateTime object 
// the "now" parameter is for get the current date, 
// but that work with a date recived from a database 
// ex. replace "now" by '2022-04-04 05:05:05'
$dateTimeObj = new DateTime('now', new DateTimeZone('Europe/Paris'));

// format the date according to your preferences
// the 3 params are [ DateTime object, ICU date scheme, string locale ]
$dateFormatted = 
IntlDateFormatter::formatObject( 
  $dateTimeObj, 
  'eee d MMMM y à HH:mm', 
  'fr' 
);

// test :
echo ucwords($dateFormatted);

// output : Jeu. 7 Avril 2022 à 04:56
like image 65
SNS - Web et Informatique Avatar answered Sep 04 '25 17:09

SNS - Web et Informatique


I've chosen to use php81_bc/strftime composer package as a replacement.

Here the documentation.

Pay attention that the output could be different from native strftime 'cause php81_bc/strftime uses a different library for locale aware formatting (ICU).

Note that output can be slightly different between libc sprintf and this function as it is using ICU.

like image 29
nulll Avatar answered Sep 04 '25 18:09

nulll