Skip to content

Commit 80694ca

Browse files
committed
DateTime: constructor accepts timezone as string
1 parent bc908ff commit 80694ca

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/Utils/DateTime.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,16 @@ public static function createFromFormat(
9999
if (is_string($timezone)) {
100100
$timezone = new \DateTimeZone($timezone);
101101
}
102-
103102
$date = parent::createFromFormat($format, $datetime, $timezone);
104103
return $date ? static::from($date) : false;
105104
}
106105

107106

108-
public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = null)
107+
public function __construct(string $datetime = 'now', \DateTimeZone|string|null $timezone = null)
109108
{
109+
if (is_string($timezone)) {
110+
$timezone = new \DateTimeZone($timezone);
111+
}
110112
$this->apply($datetime, $timezone, true);
111113
}
112114

tests/Utils/DateTime.construct.phpt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,15 @@ test('Timezone handling', function () {
9191
$dt = new DateTime('2024-11-11', $utcTz);
9292
Assert::same($utcTz->getName(), $dt->getTimezone()->getName(), 'Absolute date string uses provided timezone (UTC)');
9393
Assert::same('2024-11-11 00:00:00 UTC (+00:00)', $dt->format('Y-m-d H:i:s T (P)'));
94+
95+
// Timezone as string
96+
$dt = new DateTime('2024-06-01 12:00:00', 'Europe/Prague');
97+
Assert::same('Europe/Prague', $dt->getTimezone()->getName());
98+
99+
// Invalid timezone
100+
Assert::exception(function() {
101+
new DateTime('2024-06-01 12:00:00', 'Invalid/Timezone');
102+
}, Throwable::class);
94103
});
95104

96105

0 commit comments

Comments
 (0)