From 463f957919065d5c7324edb66d5484dd5d8ed2e2 Mon Sep 17 00:00:00 2001 From: Louis Fortunier Date: Thu, 14 Nov 2024 14:39:53 +0100 Subject: [PATCH] Add `DateUtils::getFormattedShortMonth` + tests Return short month locale format --- CHANGELOG_add_formatted_short_month.md | 2 ++ src/Utils/DateUtils.php | 25 +++++++++++++++++++++++++ tests/Utils/DateUtilsTest.php | 17 +++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 CHANGELOG_add_formatted_short_month.md diff --git a/CHANGELOG_add_formatted_short_month.md b/CHANGELOG_add_formatted_short_month.md new file mode 100644 index 0000000..53b735a --- /dev/null +++ b/CHANGELOG_add_formatted_short_month.md @@ -0,0 +1,2 @@ +### Added +- `DateUtils::getFormattedShortMonth` + tests Return short month locale format \ No newline at end of file diff --git a/src/Utils/DateUtils.php b/src/Utils/DateUtils.php index c7ed9d8..fcf7f02 100644 --- a/src/Utils/DateUtils.php +++ b/src/Utils/DateUtils.php @@ -455,6 +455,31 @@ public static function getFormattedLongMonth(\DateTime $date, string $locale = ' return ucfirst((string) $dateFormatter->format($date)); } + /** + * Return short month locale format, substring 3 char except "Juin" + * + *
+     * 
+     * 
+ * The above example will output: + *
+     * Jan
+     * 
+ */ + public static function getFormattedShortMonth(\DateTime $date, string $locale = 'fr_FR'): string + { + $month = self::getFormattedLongMonth($date, $locale); + + // It must be "Juin" in full otherwise there be multiple "Jui." key with "Juillet" + if ($month === 'Juin') { + return $month; + } + + return mb_substr((string)$month, 0, 3); + } + /** * Return full month year locale format * diff --git a/tests/Utils/DateUtilsTest.php b/tests/Utils/DateUtilsTest.php index 3600d76..1cd6fad 100644 --- a/tests/Utils/DateUtilsTest.php +++ b/tests/Utils/DateUtilsTest.php @@ -1220,6 +1220,23 @@ public function getGetFormattedLongMonthProvider(): array ]; } + /** + * @dataProvider getGetFormattedShortMonthProvider + */ + public function testGetFormattedShortMonth(string $expected, string $date, string $locale): void + { + $this->assertEquals($expected, DateUtils::getFormattedShortMonth(new \DateTime($date), $locale)); + } + + public function getGetFormattedShortMonthProvider(): array + { + return [ + 'Jan (fr)' => ['Jan', '2022-01-15', 'fr_FR'], + 'Juin' => ['Juin', '2020-06-01', 'fr_FR'], + 'Jan (en)' => ['Jan', '2020-01-01', 'en_EN'], + ]; + } + /** * @dataProvider getGetFormattedLongMonthYearsProvider */