diff --git a/src/Chronos.php b/src/Chronos.php index ada7963..635c109 100644 --- a/src/Chronos.php +++ b/src/Chronos.php @@ -694,9 +694,11 @@ protected static function applyTestNowToMissingComponents( $hasMicro = (bool)array_intersect($formatChars, ['u', 'v']); // If the format includes '!' or '|', PHP resets unspecified components to Unix epoch or zero - // In that case, we should not override with testNow + // If 'U' is present, all components are set from the Unix timestamp + // In these cases, we should not override with testNow $hasReset = in_array('!', $formatChars, true) || in_array('|', $formatChars, true); - if ($hasReset) { + $hasUnixTimestamp = in_array('U', $formatChars, true); + if ($hasReset || $hasUnixTimestamp) { return $dateTime; } diff --git a/tests/TestCase/DateTime/CreateFromFormatTest.php b/tests/TestCase/DateTime/CreateFromFormatTest.php index 91318db..bdf826b 100644 --- a/tests/TestCase/DateTime/CreateFromFormatTest.php +++ b/tests/TestCase/DateTime/CreateFromFormatTest.php @@ -111,6 +111,22 @@ public function testCreateFromFormatWithTestNowMicroseconds() $this->assertSame(123456, $d->micro); } + public function testCreateFromFormatWithTestNowUnixTimestamp() + { + // Unix timestamp ('U' format) sets all components, should not use testNow + Chronos::setTestNow(new Chronos('2020-12-01 14:30:45')); + $d = Chronos::createFromFormat('U', '0'); + $this->assertDateTime($d, 1970, 1, 1, 0, 0, 0); + } + + public function testCreateFromFormatWithTestNowNegativeUnixTimestamp() + { + // Negative Unix timestamp should also not use testNow + Chronos::setTestNow(new Chronos('2020-12-01 14:30:45')); + $d = Chronos::createFromFormat('U', '-1000'); + $this->assertDateTime($d, 1969, 12, 31, 23, 43, 20); + } + public function testCreateFromFormatWithTimezoneString() { $d = Chronos::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11', 'Europe/London');