Skip to content

Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.

merge improve date formatting with IntlDateFormatter fallback (#974)

Mercury233b2c565f74c6d
diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.php
index 3f3c16f..99d91db 100644
--- a/includes/list_subscriptions.php
+++ b/includes/list_subscriptions.php
@@ -110,20 +110,31 @@ function formatDate($date, $lang = 'en')
// Determine the date format based on whether the year matches the current year
$dateFormat = ($currentYear == $dateYear) ? 'MMM d' : 'MMM yyyy';
- // Validate the locale and fallback to 'en' if unsupported
- if (!in_array($lang, ResourceBundle::getLocales(''))) {
- $lang = 'en'; // Fallback to English
- }
+ // Try to create an IntlDateFormatter; if it fails, fallback to 'en'
+ try {
+ $formatter = new IntlDateFormatter(
+ $lang,
+ IntlDateFormatter::SHORT,
+ IntlDateFormatter::NONE,
+ null,
+ null,
+ $dateFormat
+ );
- // Create an IntlDateFormatter instance for the specified language
- $formatter = new IntlDateFormatter(
- $lang,
- IntlDateFormatter::SHORT,
- IntlDateFormatter::NONE,
- null,
- null,
- $dateFormat
- );
+ if (!$formatter) {
+ throw new Exception('Failed to create IntlDateFormatter with language: ' . $lang);
+ }
+ } catch (Throwable $e) {
+ $lang = 'en'; // Fallback to English on error
+ $formatter = new IntlDateFormatter(
+ $lang,
+ IntlDateFormatter::SHORT,
+ IntlDateFormatter::NONE,
+ null,
+ null,
+ $dateFormat
+ );
+ }
// Format the date
$formattedDate = $formatter->format(new DateTime($date));
diff --git a/index.php b/index.php
index 43d643a..5459c4a 100644
--- a/index.php
+++ b/index.php
@@ -32,21 +32,32 @@ function formatDate($date, $lang = 'en')
// Determine the date format based on whether the year matches the current year
$dateFormat = ($currentYear == $dateYear) ? 'MMM d' : 'MMM yyyy';
- // Validate the locale and fallback to 'en' if unsupported
- if (!in_array($lang, ResourceBundle::getLocales(''))) {
- $lang = 'en'; // Fallback to English
+ // Try to create an IntlDateFormatter; if it fails, fallback to 'en'
+ try {
+ $formatter = new IntlDateFormatter(
+ $lang,
+ IntlDateFormatter::SHORT,
+ IntlDateFormatter::NONE,
+ null,
+ null,
+ $dateFormat
+ );
+
+ if (!$formatter) {
+ throw new Exception('Failed to create IntlDateFormatter with language: ' . $lang);
+ }
+ } catch (Throwable $e) {
+ $lang = 'en'; // Fallback to English on error
+ $formatter = new IntlDateFormatter(
+ $lang,
+ IntlDateFormatter::SHORT,
+ IntlDateFormatter::NONE,
+ null,
+ null,
+ $dateFormat
+ );
}
- // Create an IntlDateFormatter instance for the specified language
- $formatter = new IntlDateFormatter(
- $lang,
- IntlDateFormatter::SHORT,
- IntlDateFormatter::NONE,
- null,
- null,
- $dateFormat
- );
-
// Format the date
$formattedDate = $formatter->format(new DateTime($date));