Home > Net >  PHP 8.1: strftime() is deprecated
PHP 8.1: strftime() is deprecated

Time:02-01

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'))

CodePudding user response:

Hey I have also experienced this issue as well so after some research on PHP's official documentation here what I found! https://www.php.net/manual/en/function.strftime.php
They are saying that it is depricated and use setlocale() function this also work same as strftime().
For more information please visit official PHP docs of setlocale() https://www.php.net/manual/en/function.setlocale.php

CodePudding user response:

You can use the IntlDateFormatter class. The class works independently of the locales settings. With a function like this

function formatLanguage(DateTime $dt,string $format,string $language = 'en') : string {
    $curTz = $dt->getTimezone();
    if($curTz->getName() === 'Z'){
      //INTL don't know Z
      $curTz = new DateTimeZone('UTC');
    }

    $formatPattern = strtr($format,array(
        'D' => '{#1}',
        'l' => '{#2}',
        'M' => '{#3}',
        'F' => '{#4}',
      ));
      $strDate = $dt->format($formatPattern);
      $regEx = '~\{#\d\}~';
      while(preg_match($regEx,$strDate,$match)) {
        $IntlFormat = strtr($match[0],array(
          '{#1}' => 'E',
          '{#2}' => 'EEEE',
          '{#3}' => 'MMM',
          '{#4}' => 'MMMM',
        ));
        $fmt = datefmt_create( $language ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
        $curTz, IntlDateFormatter::GREGORIAN, $IntlFormat);
        $replace = $fmt ? datefmt_format( $fmt ,$dt) : "???";
        $strDate = str_replace($match[0], $replace, $strDate);
      }

    return $strDate;
}

you can use format parameters like for datetime.

$dt = date_create('2022-01-31');
echo formatLanguage($dt, 'd F Y','pl');  //31 stycznia 2022

There are extension classes for DateTime that have such functions integrated as methods.

echo dt::create('2022-01-31')->formatL('d F Y','pl');
  •  Tags:  
  • Related