Skip to content

Commit

Permalink
Merge pull request #2028 from DoSomething/millisecond-date-bug
Browse files Browse the repository at this point in the history
Fix issue parsing millisecond-precision dates before 1970.
  • Loading branch information
Smolevich authored Apr 23, 2020
2 parents 3d58b4b + 2f92654 commit 736415e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Jenssegers/Mongodb/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,13 @@ protected function asDateTime($value)
{
// Convert UTCDateTime instances.
if ($value instanceof UTCDateTime) {
return Date::createFromTimestampMs($value->toDateTime()->format('Uv'));
$date = $value->toDateTime();

$seconds = $date->format('U');
$milliseconds = abs($date->format('v'));
$timestampMs = sprintf('%d%03d', $seconds, $milliseconds);

return Date::createFromTimestampMs($timestampMs);
}

return parent::asDateTime($value);
Expand Down
8 changes: 8 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,14 @@ public function testDates(): void
$user = User::create(['name' => 'Jane Doe', 'birthday' => '2005-08-08']);
$this->assertInstanceOf(Carbon::class, $user->birthday);

// test millisecond-precision dates after 1970:
$user = User::create(['name' => 'Jane Doe', 'birthday' => new DateTime('2010-08-08 04.08.37.324')]);
$this->assertInstanceOf(Carbon::class, $user->birthday);

// test millisecond-precision dates before 1970:
$user = User::create(['name' => 'Jane Doe', 'birthday' => new DateTime('1965-08-08 04.08.37.324')]);
$this->assertInstanceOf(Carbon::class, $user->birthday);

$user = User::create(['name' => 'Jane Doe', 'entry' => ['date' => '2005-08-08']]);
$this->assertInstanceOf(Carbon::class, $user->getAttribute('entry.date'));

Expand Down

0 comments on commit 736415e

Please sign in to comment.