PHP 8.1: strftime and gmstrftime functions are deprecated

Version8.1
TypeDeprecation

strftime and gmstrftime functions format a Unix timestamp based on the current locale set using the setlocale function. gmstrftime function is similar to strftime, except that it returns the time in Greenwich Mean Time (GMT).

setlocale function sets the locale setting to the PHP process, rather than the current working thread. This can result in sudden change in the locale if another thread calls setlocale function. This can be specially troublesome if PHP is used in a multi-threaded Server API (such as mod_php for PHP).

PHP offers locale-independent and locale-aware time formatting APIs that are better, feature-rich, and more intuitive. In PHP 8.1 and later, strftime and gmstrftime are deprecated, and using them emits a deprecation notice. These functions will be removed in PHP 9.0.

strftime('%D');
gmstrftime('%D');
PHP Deprecated:  Function strftime() is deprecated in ... on line ...
PHP Deprecated:  Function gmstrftime() is deprecated in ... on line ...

Replacements

For locale-aware date/time formatting, use IntlDateFormatter::format (requires Intl extension).

In a real-life and ideal use case, the IntlDateFormatter object is instantiated once based on the user's locale information, and the object instance can is used whenever necessary.

- setlocale(LC_TIME, "en_US");
- echo strftime('%x', time());
+ $formatter = new IntlDateFormatter('en_US', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
+ echo $formatter->format(time());

For locale-independent date/time formatting, use the date() function or DateTime::format / DateTimeImmutable::format. Note that this can result in different time formats on applications that relied on setlocale to set the format. Explicitly setting the date format can remedy this.

- setlocale(LC_TIME, "en_US");
- echo strftime('%F', time());
+ echo date('Y-m-d', time());

DateTimeImmutable::format can also format a DateTimeImmutable object:

- setlocale(LC_TIME, "en_US");
- echo strftime('%F', time());
+ $date = DateTimeImmutable::createFromFormat('U', time());
+ echo $date->format('Y-m-d');

Related Changes

Backwards Compatibility Impact

Using strftime / gmstrftime functions result in a deprecation notice in PHP 8.1 and later. These functions will be removed in PHP 9.0.

Depending on the intended use case of functions, the replacements can provide a identical output, or a rather accurate output if the functions were used without expecting locale-aware formatting.

For locale-aware date/time formatting, Intl extension provides a more robust and complete solution without the undesired behavior of the setlocale function.


RFC Implementation