Skip to content

Commit 6545827

Browse files
committed
initialize the current time with midnight before modifying the date
1 parent ecba44b commit 6545827

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

DatePoint.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,21 @@ public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone =
3232

3333
if (\PHP_VERSION_ID < 80300) {
3434
try {
35-
$timezone = (new parent($datetime, $timezone ?? $now->getTimezone()))->getTimezone();
35+
$builtInDate = new parent($datetime, $timezone ?? $now->getTimezone());
36+
$timezone = $builtInDate->getTimezone();
3637
} catch (\Exception $e) {
3738
throw new \DateMalformedStringException($e->getMessage(), $e->getCode(), $e);
3839
}
3940
} else {
40-
$timezone = (new parent($datetime, $timezone ?? $now->getTimezone()))->getTimezone();
41+
$builtInDate = new parent($datetime, $timezone ?? $now->getTimezone());
42+
$timezone = $builtInDate->getTimezone();
4143
}
4244

4345
$now = $now->setTimezone($timezone)->modify($datetime);
46+
47+
if ('00:00:00.000000' === $builtInDate->format('H:i:s.u')) {
48+
$now = $now->setTime(0, 0);
49+
}
4450
} elseif (null !== $timezone) {
4551
$now = $now->setTimezone($timezone);
4652
}

Tests/DatePointTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,19 @@ public function testModify()
5757
$this->expectExceptionMessage('Failed to parse time string (Bad Date)');
5858
$date->modify('Bad Date');
5959
}
60+
61+
/**
62+
* @testWith ["2024-04-01 00:00:00.000000", "2024-04"]
63+
* ["2024-04-09 00:00:00.000000", "2024-04-09"]
64+
* ["2024-04-09 03:00:00.000000", "2024-04-09 03:00"]
65+
* ["2024-04-09 00:00:00.123456", "2024-04-09 00:00:00.123456"]
66+
*/
67+
public function testTimeDefaultsToMidnight(string $expected, string $datetime)
68+
{
69+
$date = new \DateTimeImmutable($datetime);
70+
$this->assertSame($expected, $date->format('Y-m-d H:i:s.u'));
71+
72+
$date = new DatePoint($datetime);
73+
$this->assertSame($expected, $date->format('Y-m-d H:i:s.u'));
74+
}
6075
}

0 commit comments

Comments
 (0)