Skip to content

Commit bf7e324

Browse files
committed
feat: Allow default date time format to be changed
1 parent e36858d commit bf7e324

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/Convert/Convert.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ final class Convert
1919
{
2020
private static DateTimeZone|null $dateTimeZone = null;
2121

22+
private static string $dateTimeFormat = 'c';
23+
2224
/** @return ($value is null ? null : bool) */
2325
public static function asBool(mixed $value): bool|null
2426
{
@@ -142,7 +144,7 @@ public static function asDateTimeString(mixed $value): string|null
142144

143145
$value = asDateTimeImmutable($value);
144146

145-
return $value->format('c');
147+
return $value->format(self::dateTimeFormat());
146148
}
147149

148150
public static function timeZone(DateTimeZone|string|null $timeZone = null): DateTimeZone
@@ -157,4 +159,13 @@ public static function timeZone(DateTimeZone|string|null $timeZone = null): Date
157159

158160
return self::$dateTimeZone;
159161
}
162+
163+
public static function dateTimeFormat(string|null $dateTimeFormat = null): string
164+
{
165+
if ($dateTimeFormat !== null) {
166+
self::$dateTimeFormat = $dateTimeFormat;
167+
}
168+
169+
return self::$dateTimeFormat;
170+
}
160171
}

tests/Convert/AsDateTimeStringTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,18 @@
2222
#[CoversFunction('\Plook\TypeGuard\Convert\asString')]
2323
final class AsDateTimeStringTest extends TestCase
2424
{
25+
private readonly string $originalDateTimeFormat;
26+
27+
protected function setUp(): void
28+
{
29+
$this->originalDateTimeFormat = Convert::dateTimeFormat();
30+
}
31+
32+
protected function tearDown(): void
33+
{
34+
Convert::dateTimeFormat($this->originalDateTimeFormat);
35+
}
36+
2537
public function testConvertsStrings(): void
2638
{
2739
self::assertSame('2010-09-08T07:06:05+02:00', asDateTimeString('2010-09-08T07:06:05+02:00'));
@@ -35,6 +47,13 @@ public function testConvertsStringables(): void
3547
);
3648
}
3749

50+
public function testDateTimeFormatCanBeChanged(): void
51+
{
52+
Convert::dateTimeFormat('Y-m-d');
53+
54+
self::assertSame('2010-09-08', asDateTimeString('2010-09-08T07:06:05+02:00'));
55+
}
56+
3857
public function testDoesNotTouchNull(): void
3958
{
4059
self::assertNull(asDateTimeString(null));

0 commit comments

Comments
 (0)