Skip to content

Strftime replacement

gtbu edited this page Jan 20, 2025 · 8 revisions

In PHP 8.1 and later versions the function strftime is deprecated

strftime([string] $format, [?] [int] $timestamp = [null]: [string]|[false]

  • To sustain compatibility, the old strftime was replaced with an emulated function strftime und added as strftime.php so that old code still functions.

  • You can instead use the DateTimeImmutable class to achieve similar functionality as the strftime() function. $date = new DateTimeImmutable('now'); echo $date->format('%B %d, %Y'); // Outputs "March 24, 2024"

$now = new \DateTimeImmutable();
$timestamp = $now->setTimezone(new \DateTimeZone('UTC'));

$day = new \DateTimeImmutable('2024-03-24');
$day->setTimezone(new \DateTimeZone('UTC'));

$week = ($timestamp->format('z') - $day->format('z')) / 7;
$week = 1 + floor($week);

$week_number = sprintf('% 2u', $week);

$day_of_week = $timestamp->format('w');
$day_of_week = 1 + $day_of_week;

$day_of_week_number = sprintf('% 2u', $day_of_week);

$time = $timestamp->format('H:i:s');
$time_number = sprintf('% 2u', $time);

$date = $timestamp->format('d.m.Y');
$date_number = sprintf('% 2u', $date);

$hour = $timestamp->format('G');
$hour_number = sprintf('% 2u', $hour);

$minute = $timestamp->format('g');
$minute_number = sprintf('% 2u', $minute);

$day = $timestamp->format('j');
$day_number = sprintf('% 2u', $day);

$month = $timestamp->format('m');
$month_number = sprintf('% 2u', $month);

$year = $timestamp->format('Y');
$year_number = sprintf('% 2u', $year);

$week_number_of_year = sprintf('% 2u', $timestamp->format('W'));

$day_of_year = $timestamp->format('z') + 1;
$day_of_year_number = sprintf('% 2u', $day_of_year);

$hour_of_day = $timestamp->format('H');
$hour_of_day_number = sprintf('% 2u', $hour_of_day);

$minute_of_hour = $timestamp->format('i');
$minute_of_hour_number = sprintf('% 2u', $minute_of_hour);

$second = $timestamp->format('s');
$second_number = sprintf('% 2u', $second);

echo "$week_number_of_year-$week_number-$day_number_of_year\n";
echo "$hour_number:$minute_number:$second_number\n";
echo "Day of week number: $day_of_week_number\n";
echo "Date: $date_number\n";
echo "Hour: $hour_number\n";
echo "Minute: $minute_number\n";
echo "Year: $year_number\n";
echo "Month: $month_number\n";
echo "Week number: $week_number\n";
echo "Day of year: $day_of_year_number\n";
echo "Hour of day: $hour_of_day_number\n";
echo "Minute of hour: $minute_of_hour_number\n";
echo "Second: $second_number\n";

$date = DateTimeImmutable::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');

Clone this wiki locally