Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active April 4, 2023 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stemar/36c7ffa31a6167945d547ae6cc89dc0e to your computer and use it in GitHub Desktop.
Save stemar/36c7ffa31a6167945d547ae6cc89dc0e to your computer and use it in GitHub Desktop.
Localize datetime using encapsulated IntlDateFormatter functions
<?php
/**
* Localize datetime using encapsulated IntlDateFormatter functions
*
* @param IntlCalendar|DateTimeInterface|array|string|int|float $datetime
* @param array $kwargs
* @link https://www.php.net/manual/en/intldateformatter.format.php
* @link https://www.php.net/manual/en/intldateformatter.create.php
* @link https://www.php.net/manual/en/class.locale.php
* @return string|false
*/
function datetime_format($datetime, array $kwargs = []) {
extract($kwargs + [
'date_type' => IntlDateFormatter::SHORT,
'time_type' => IntlDateFormatter::SHORT,
'locale' => substr(Locale::getDefault(), 0, 5) ?: NULL,
'pattern' => NULL,
'timezone' => NULL,
]);
$fmt = datefmt_create($locale, $date_type, $time_type, $timezone, NULL, $pattern);
return datefmt_format($fmt, $datetime);
}
@stemar
Copy link
Author

stemar commented Apr 2, 2023

datefmt_create() arguments

datefmt_create(?string $locale, int $dateType = IntlDateFormatter::FULL, int $timeType = IntlDateFormatter::FULL, IntlTimeZone|DateTimeZone|string|null $timezone = null, IntlCalendar|int|null $calendar = null, ?string $pattern = null)

locale argument

If NULL, it will lookup its default value in this order:

  1. ini_get('intl.default_locale')
  2. setlocale(LC_ALL, 0);
  3. $LANG value from the set locale of the operating system.

date type argument

If NULL, it will select IntlDateFormatter::FULL.

  • IntlDateFormatter::NONE to skip the output of the date
  • IntlDateFormatter::FULL with weekday
  • IntlDateFormatter::LONG
  • IntlDateFormatter::MEDIUM
  • IntlDateFormatter::SHORT

time type argument

If NULL, it will select IntlDateFormatter::FULL.

  • IntlDateFormatter::NONE to skip the output of the time
  • IntlDateFormatter::FULL with time zone description
  • IntlDateFormatter::LONG
  • IntlDateFormatter::MEDIUM
  • IntlDateFormatter::SHORT

time zone argument

If NULL, it will lookup its default value in this order:

  1. date_default_timezone_get()
  2. ini_get('date.timezone')
  3. 'UTC'

calendar argument

If NULL, it will select IntlDateFormatter::GREGORIAN.

pattern argument

If not NULL, it will override date type and time type arguments.
If NULL, it will defer to date type and time type arguments.

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