Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Last active March 20, 2025 11:19
Show Gist options
  • Select an option

  • Save bohwaz/42fc223031e2b2dd2585aab159a20f30 to your computer and use it in GitHub Desktop.

Select an option

Save bohwaz/42fc223031e2b2dd2585aab159a20f30 to your computer and use it in GitHub Desktop.
strftime() replacement function for PHP 8.1
<?php
namespace PHP81_BC;
/**
* Locale-formatted strftime using \IntlDateFormatter (PHP 8.1 compatible)
* This provides a cross-platform alternative to strftime() for when it will be removed from PHP.
* Note that output can be slightly different between libc sprintf and this function as it is using ICU.
*
* Usage:
* use function \PHP81_BC\strftime;
* echo strftime('%A %e %B %Y %X', new \DateTime('2021-09-28 00:00:00'), 'fr_FR');
*
* Original use:
* \setlocale('fr_FR.UTF-8', LC_TIME);
* echo \strftime('%A %e %B %Y %X', strtotime('2021-09-28 00:00:00'));
*
* @param string $format Date format
* @param integer|string|DateTime $timestamp Timestamp
* @return string
* @author BohwaZ <https://bohwaz.net/>
*/
function strftime(string $format, $timestamp = null, ?string $locale = null): string
{
if (null === $timestamp) {
$timestamp = new \DateTime;
}
elseif (is_numeric($timestamp)) {
$timestamp = date_create('@' . $timestamp);
if ($timestamp) {
$timestamp->setTimezone(new \DateTimezone(date_default_timezone_get()));
}
}
elseif (is_string($timestamp)) {
$timestamp = date_create($timestamp);
}
if (!($timestamp instanceof \DateTimeInterface)) {
throw new \InvalidArgumentException('$timestamp argument is neither a valid UNIX timestamp, a valid date-time string or a DateTime object.');
}
$locale = substr((string) $locale, 0, 5);
$intl_formats = [
'%a' => 'EEE', // An abbreviated textual representation of the day Sun through Sat
'%A' => 'EEEE', // A full textual representation of the day Sunday through Saturday
'%b' => 'MMM', // Abbreviated month name, based on the locale Jan through Dec
'%B' => 'MMMM', // Full month name, based on the locale January through December
'%h' => 'MMM', // Abbreviated month name, based on the locale (an alias of %b) Jan through Dec
];
$intl_formatter = function (\DateTimeInterface $timestamp, string $format) use ($intl_formats, $locale) {
$tz = $timestamp->getTimezone();
$date_type = \IntlDateFormatter::FULL;
$time_type = \IntlDateFormatter::FULL;
$pattern = '';
// %c = Preferred date and time stamp based on locale
// Example: Tue Feb 5 00:45:10 2009 for February 5, 2009 at 12:45:10 AM
if ($format == '%c') {
$date_type = \IntlDateFormatter::LONG;
$time_type = \IntlDateFormatter::SHORT;
}
// %x = Preferred date representation based on locale, without the time
// Example: 02/05/09 for February 5, 2009
elseif ($format == '%x') {
$date_type = \IntlDateFormatter::SHORT;
$time_type = \IntlDateFormatter::NONE;
}
// Localized time format
elseif ($format == '%X') {
$date_type = \IntlDateFormatter::NONE;
$time_type = \IntlDateFormatter::MEDIUM;
}
else {
$pattern = $intl_formats[$format];
}
return (new \IntlDateFormatter($locale, $date_type, $time_type, $tz, null, $pattern))->format($timestamp);
};
// Same order as https://www.php.net/manual/en/function.strftime.php
$translation_table = [
// Day
'%a' => $intl_formatter,
'%A' => $intl_formatter,
'%d' => 'd',
'%e' => function ($timestamp) {
return sprintf('% 2u', $timestamp->format('j'));
},
'%j' => function ($timestamp) {
// Day number in year, 001 to 366
return sprintf('%03d', $timestamp->format('z')+1);
},
'%u' => 'N',
'%w' => 'w',
// Week
'%U' => function ($timestamp) {
// Number of weeks between date and first Sunday of year
$day = new \DateTime(sprintf('%d-01 Sunday', $timestamp->format('Y')));
return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7);
},
'%V' => 'W',
'%W' => function ($timestamp) {
// Number of weeks between date and first Monday of year
$day = new \DateTime(sprintf('%d-01 Monday', $timestamp->format('Y')));
return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7);
},
// Month
'%b' => $intl_formatter,
'%B' => $intl_formatter,
'%h' => $intl_formatter,
'%m' => 'm',
// Year
'%C' => function ($timestamp) {
// Century (-1): 19 for 20th century
return floor($timestamp->format('Y') / 100);
},
'%g' => function ($timestamp) {
return substr($timestamp->format('o'), -2);
},
'%G' => 'o',
'%y' => 'y',
'%Y' => 'Y',
// Time
'%H' => 'H',
'%k' => function ($timestamp) {
return sprintf('% 2u', $timestamp->format('G'));
},
'%I' => 'h',
'%l' => function ($timestamp) {
return sprintf('% 2u', $timestamp->format('g'));
},
'%M' => 'i',
'%p' => 'A', // AM PM (this is reversed on purpose!)
'%P' => 'a', // am pm
'%r' => 'h:i:s A', // %I:%M:%S %p
'%R' => 'H:i', // %H:%M
'%S' => 's',
'%T' => 'H:i:s', // %H:%M:%S
'%X' => $intl_formatter, // Preferred time representation based on locale, without the date
// Timezone
'%z' => 'O',
'%Z' => 'T',
// Time and Date Stamps
'%c' => $intl_formatter,
'%D' => 'm/d/Y',
'%F' => 'Y-m-d',
'%s' => 'U',
'%x' => $intl_formatter,
];
$out = preg_replace_callback('/(?<!%)(%[a-zA-Z])/', function ($match) use ($translation_table, $timestamp) {
if ($match[1] == '%n') {
return "\n";
}
elseif ($match[1] == '%t') {
return "\t";
}
if (!isset($translation_table[$match[1]])) {
throw new \InvalidArgumentException(sprintf('Format "%s" is unknown in time format', $match[1]));
}
$replace = $translation_table[$match[1]];
if (is_string($replace)) {
return $timestamp->format($replace);
}
else {
return $replace($timestamp, $match[1]);
}
}, $format);
$out = str_replace('%%', '%', $out);
return $out;
}
@alphp

alphp commented Mar 13, 2022

Copy link
Copy Markdown

I've converted the Gist to a GitHub project so I can install it with composer:
https://github.com/alphp/strftime
https://packagist.org/packages/php81_bc/strftime

@bohwaz

bohwaz commented Mar 13, 2022

Copy link
Copy Markdown
Author

I've converted the Gist to a GitHub project so I can install it with composer: https://github.com/alphp/strftime https://packagist.org/packages/php81_bc/strftime

great thanks :)

@krmgns

krmgns commented Apr 11, 2022

Copy link
Copy Markdown

And I used it for my project, so it works without IntlDateFormatter.
Thank you! https://github.com/froq/froq-datetime/blob/6.0.0-dev/src/format/Formatter.php

@francoisjacquet

Copy link
Copy Markdown

Thanks for this compatibility function!

I would like to report this behavior:

echo strftime( '%X', strtotime( '2022-04-13 21:12:26' ) );

Prints 09:12:26 PM as expected

while with your function

use function \PHP81_BC\strftime;

echo strftime( '%X', strtotime( '2022-04-13 21:12:26' ) );

Prints 7:12:26 PM

Tried setting the timezone in PHP, but this did not have any effect.

Any idea?

@francoisjacquet

francoisjacquet commented Apr 13, 2022

Copy link
Copy Markdown

Re: the fix to my issue:

use function \PHP81_BC\strftime;

echo strftime( '%X', '2022-04-13 21:12:26' );

And line https://gist.github.com/bohwaz/42fc223031e2b2dd2585aab159a20f30#file-php-8-1-strftime-php-L31=
Remove the '!' . so date_create() can actually create the date from string!

Question: what was the '!' . exclamation mark part was intended to do?

@bohwaz

bohwaz commented Apr 14, 2022

Copy link
Copy Markdown
Author

My bad it was a mix-up with DateTime::createFromFormat

You should check out https://github.com/alphp/strftime from @alphp which has the latest fixes :)

@bohwaz

bohwaz commented Apr 14, 2022

Copy link
Copy Markdown
Author
use function \PHP81_BC\strftime;

echo strftime( '%X', strtotime( '2022-04-13 21:12:26' ) );

Prints 7:12:26 PM

Tried setting the timezone in PHP, but this did not have any effect.

Any idea?

Adding this in the if (is_numeric(... block should fix it:

		if ($timestamp) {
			$timestamp->setTimezone(new \DateTimezone(date_default_timezone_get()));
		}

I updated the gist.

@gtbu

gtbu commented May 24, 2022

Copy link
Copy Markdown

Why do You use a namespace and not a class ?

I call this function (in TypesetterCMS , tool.php line 2191) in a namespace gp and get the error : ExecInfo() Fatal Error: Call to undefined function gp\PHP81_BC\strftime() .
With \PHP81_BC\strftime($match[0], $time); ExecInfo() Fatal Error: Call to undefined function PHP81_BC\strftime()

Sorry - that was my xampp and not gp (use function \PHP81_BC\strftime;) - missing ;extension=php_intl.dll ....

@bohwaz

bohwaz commented May 24, 2022

Copy link
Copy Markdown
Author

Using a namespaced function makes it easier to replace the built-in strftime function. It's just a simple way to overwrite the default strftime function.

@hobbez

hobbez commented Jun 16, 2022

Copy link
Copy Markdown

Output for %c does not appear to be correct: June 16, 2022 at 4:11 PM
strftime("%c") should be: Jun 16 16:11:00 2022

@inpresif

Copy link
Copy Markdown

Thanks for the function, it works perfectly for my project which lets people reformat date/time on our API output feature

@arne-s

arne-s commented Dec 4, 2022

Copy link
Copy Markdown

Thanks! Saved me some time updating a crappy legacy project to 8.1

@TheWitness

Copy link
Copy Markdown

Actually, worked like a charm!

@francoisjacquet

Copy link
Copy Markdown

Be warned: This line https://gist.github.com/bohwaz/42fc223031e2b2dd2585aab159a20f30#file-php-8-1-strftime-php-L31 will produce a fatal error in case the date.timezone ini setting is not a valid timezone.

Uncaught Exception: DateTime::__construct(): Invalid date.timezone value 'Afrique/Brazzaville', we selected the timezone 'UTC' for now.

This can happen with cPanel > PHP Selector > Options > date.timezone.

Note though, I have tried to inject an invalid timezone with PHP FPM on my box, but the timezone automatically is reset to UTC.

This can be fixed by, beforehand in your code, adding for example:

	// Fix PHP error if date.timezone ini setting is an invalid timezone identifier.
	date_default_timezone_set( date_default_timezone_get() );

@bohwaz

bohwaz commented Mar 31, 2023

Copy link
Copy Markdown
Author

@francoisjacquet thanks. Actually that's the exact same line I'm using in all my PHP code :)

But I don't think it's the role of this snippet to do that kind of stuff.

@gtbu

gtbu commented Nov 6, 2023

Copy link
Copy Markdown

With php 8.2. i get the error Class "IntlDateFormatter" not found - in ....\thirdparty\time\strftime.php on line: 54 (with php 8.1 it functions)

@bohwaz

bohwaz commented Nov 6, 2023

Copy link
Copy Markdown
Author

With php 8.2. i get the error Class "IntlDateFormatter" not found - in ....\thirdparty\time\strftime.php on line: 54 (with php 8.1 it functions)

Just install php8.2-intl :)

@gtbu

gtbu commented Nov 7, 2023

Copy link
Copy Markdown

No - intl is of course installed . With php 8.1 the code functions.
The Class "IntlDateFormatter is a standard php-class. What helped was to add
use DateTime;
use DateTimeZone;
use DateTimeInterface;
use Exception;
use IntlDateFormatter;
use IntlGregorianCalendar;
use InvalidArgumentException;

@gtbu

gtbu commented Mar 24, 2024

Copy link
Copy Markdown

You use return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7);

  • Some common mistakes when using sprintf include forgetting to allocate enough space for the output, passing invalid pointers to the function, or providing incorrect format specifiers. These errors can lead to unexpected behavior, such as truncated strings or memory corruption.
    To avoid these issues one should consider using safer alternatives to sprintf, such as the newer snprintf function, which allows to specify the maximum number of characters to write to the output buffer. This helps prevent potential buffer overflow vulnerabilities and ensures that your code behaves predictably.

Example
$a = 123; $b = 456; $c = 789;
$format = '%d + %d + %d = %f';
$values = array($a, $b, $c);
$result = '';
$output_len = snprintf($result, sizeof($result), $format, $values);
if ($output_len >= sizeof($result)) {
echo "Output string truncated! Lost " . ($output_len - sizeof($result) + 1) . " characters.\n";
} else {
printf("%s", $result);
}

@bohwaz

bohwaz commented Mar 24, 2024

Copy link
Copy Markdown
Author

What the hell are you talking about, PHP does not have a snprintf function.

@gtbu

gtbu commented Mar 24, 2024

Copy link
Copy Markdown

Sorry - that was Ai - it assured me that it functions with c++ and php- just delete it.
Perhaps from https://github.com/php/php-src/blob/master/main/snprintf.h or https://opensource.apple.com/source/apache_mod_php/apache_mod_php-131/php/main/snprintf.h.auto.html

@bohwaz

bohwaz commented Mar 24, 2024

Copy link
Copy Markdown
Author

Oh for fucks sake, stop making me lose my time with that AI nonsense.

@bohwaz

bohwaz commented Mar 24, 2024

Copy link
Copy Markdown
Author

Anyone using AI to report stuff will get blocked from me.

@jreynaert

jreynaert commented Mar 20, 2025

Copy link
Copy Markdown

We are smoothly migrating from 7.4 to 8.3 in steps. I love this function, but I’ve added an extra line.
if ( PHP_VERSION_ID < 80100 ) return strftime($format, $timestamp);

@alphp

alphp commented Mar 20, 2025

Copy link
Copy Markdown

strftime was deprecated, among other reasons, because it was inconsistent across platforms:
https://wiki.php.net/rfc/deprecations_php_8_1#strftime_and_gmstrftime

This implementation provides the same functionality but in a consistent manner.

This strftime replacement is maintained in the https://github.com/alphp/strftime repo.

And can be installed using Composer:

composer require php81_bc/strftime

Condicional use:

if ( PHP_VERSION_ID >= 81000 ) {
    use function \PHP81_BC\strftime;
}

@TheWitness

TheWitness commented Mar 20, 2025

Copy link
Copy Markdown

Nice, composer! The PHP team tossed the baby out with the bath water on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment