From 1cf75e0621a8a28d75ff8592c085bf49f95c235b Mon Sep 17 00:00:00 2001 From: Sandra Kuipers Date: Fri, 17 May 2024 10:53:03 +0800 Subject: [PATCH] Format: apply a fallback pattern to dateIntlReadable to prevent exceptions --- src/Services/Format.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Services/Format.php b/src/Services/Format.php index 6ed83f9f67..47ac828f57 100644 --- a/src/Services/Format.php +++ b/src/Services/Format.php @@ -126,22 +126,27 @@ public static function dateTime($dateString, $format = false) * Formats a YYYY-MM-DD date as a readable string with month names. * * @param DateTime|string $dateString The date string to format. - * @param string $pattern (Optional) The pattern string for Unicode formatting suppored by + * @param string $pattern (Optional) The pattern string for Unicode formatting supported by * IntlDateFormatter::setPattern(). * * See: https://unicode-org.github.io/icu/userguide/format_parse/datetime/ * Default: 'MMM d, Y' + * @param string $fallbackPattern (Optional) A fallback pattern string to use for the date using + * PHP's DateTime library if intl is not available. + * Default: 'M d, Y' * * @return string The formatted date string. */ - public static function dateIntlReadable($dateString, $pattern = 'MMM d, yyyy'): string + public static function dateIntlReadable($dateString, $pattern = 'MMM d, yyyy', $fallbackPattern = 'M d, Y'): string { if (empty($dateString)) { return ''; } + if (!static::$intlFormatterAvailable) { - throw new \Exception('IntlDateFormatter not available.'); + return static::date($dateString, $fallbackPattern); } + $formatter = new \IntlDateFormatter( static::$settings['code'], \IntlDateFormatter::FULL, @@ -184,7 +189,7 @@ public static function dateReadable($dateString, $format = '%b %e, %Y') * * @return string The formatted date string. */ - public static function dateTimeIntlReadable($dateString, $pattern = 'MMM d, yyyy HH:mm'): string + public static function dateTimeIntlReadable($dateString, $pattern = 'MMM d, yyyy HH:mm', $fallbackPattern = 'M d, Y H:i:s'): string { return static::dateIntlReadable($dateString, $pattern); } @@ -326,7 +331,7 @@ public static function relativeTime($dateString, $tooltip = true, $relativeStrin break; default: $timeDifference = 0; - $time = static::dateReadable($dateString); + $time = static::dateIntlReadable($dateString); } if ($relativeString && $timeDifference > 0) {