From 260b834da41ceda5512c219a0ca25d1ca3550719 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 9 Apr 2024 09:34:26 +0200 Subject: [PATCH] initialize the current time with midnight before modifying the date --- src/Symfony/Component/Clock/DatePoint.php | 10 ++++++++-- .../Component/Clock/Tests/DatePointTest.php | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Clock/DatePoint.php b/src/Symfony/Component/Clock/DatePoint.php index 8749f487bcd54..c3bf3160bcd39 100644 --- a/src/Symfony/Component/Clock/DatePoint.php +++ b/src/Symfony/Component/Clock/DatePoint.php @@ -32,15 +32,21 @@ public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = if (\PHP_VERSION_ID < 80300) { try { - $timezone = (new parent($datetime, $timezone ?? $now->getTimezone()))->getTimezone(); + $builtInDate = new parent($datetime, $timezone ?? $now->getTimezone()); + $timezone = $builtInDate->getTimezone(); } catch (\Exception $e) { throw new \DateMalformedStringException($e->getMessage(), $e->getCode(), $e); } } else { - $timezone = (new parent($datetime, $timezone ?? $now->getTimezone()))->getTimezone(); + $builtInDate = new parent($datetime, $timezone ?? $now->getTimezone()); + $timezone = $builtInDate->getTimezone(); } $now = $now->setTimezone($timezone)->modify($datetime); + + if ('00:00:00.000000' === $builtInDate->format('H:i:s.u')) { + $now = $now->setTime(0, 0); + } } elseif (null !== $timezone) { $now = $now->setTimezone($timezone); } diff --git a/src/Symfony/Component/Clock/Tests/DatePointTest.php b/src/Symfony/Component/Clock/Tests/DatePointTest.php index c9d7ddf10a803..191c1195465de 100644 --- a/src/Symfony/Component/Clock/Tests/DatePointTest.php +++ b/src/Symfony/Component/Clock/Tests/DatePointTest.php @@ -57,4 +57,19 @@ public function testModify() $this->expectExceptionMessage('Failed to parse time string (Bad Date)'); $date->modify('Bad Date'); } + + /** + * @testWith ["2024-04-01 00:00:00.000000", "2024-04"] + * ["2024-04-09 00:00:00.000000", "2024-04-09"] + * ["2024-04-09 03:00:00.000000", "2024-04-09 03:00"] + * ["2024-04-09 00:00:00.123456", "2024-04-09 00:00:00.123456"] + */ + public function testTimeDefaultsToMidnight(string $expected, string $datetime) + { + $date = new \DateTimeImmutable($datetime); + $this->assertSame($expected, $date->format('Y-m-d H:i:s.u')); + + $date = new DatePoint($datetime); + $this->assertSame($expected, $date->format('Y-m-d H:i:s.u')); + } }