<?php
namespace App\Util;
use DateTimeInterface;
use IntlDateFormatter;
/**
*
*/
final class LocaleDateFormatter extends IntlDateFormatter
{
/**
* @param string $locale
* @param int|null $dateType
* @param int|null $timeType
* @param $timezone
* @param $calendar
* @param string|null $pattern
*/
public function __construct(
string $locale,
?int $dateType,
?int $timeType,
$timezone = null,
$calendar = null,
?string $pattern = ''
)
{
// make sure the locale is one we support
if ( ! Locales::isLocale($locale)) {
throw new \RuntimeException(sprintf(
'Locale "%s" is not supported by the system.',
$locale
));
}
// call parent constructor
parent::__construct($locale, $dateType, $timeType, $timezone, $calendar, $pattern);
}
/**
* @param DateTimeInterface $timestamp
* @param string $pattern
* @return false|string
*/
public function formatWithPattern(DateTimeInterface $timestamp, string $pattern)
{
// obtain the old patter, if any
$previous = $this->getPattern() ?: null;
// set pattern using the new one
$this->setPattern($pattern);
// do the formatting
$formatted = $this->format($timestamp);
// restore the old pattern
$this->setPattern((string) $previous);
return $formatted;
}
}