Skip to content

Commit

Permalink
Fix date to DOS time conversion (#306)
Browse files Browse the repository at this point in the history
- Updated Time class
- Updated unit tests

> Fixes bug where DOS times are calculated incorrectly when the local machine timezone is different from UTC.
  • Loading branch information
josemmo authored Jun 24, 2024
1 parent 98299ba commit 9da34d6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
20 changes: 7 additions & 13 deletions src/Time.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,14 @@ public static function dateTimeToDosTime(DateTimeInterface $dateTime): int

$dateTime = DateTimeImmutable::createFromInterface($dateTime)->sub(new DateInterval('P1980Y'));

['year' => $year,
'mon' => $month,
'mday' => $day,
'hours' => $hour,
'minutes' => $minute,
'seconds' => $second
] = getdate($dateTime->getTimestamp());
[$year, $month, $day, $hour, $minute, $second] = explode(' ', $dateTime->format('Y n j G i s'));

return
($year << 25) |
($month << 21) |
($day << 16) |
($hour << 11) |
($minute << 5) |
($second >> 1);
((int) $year << 25) |
((int) $month << 21) |
((int) $day << 16) |
((int) $hour << 11) |
((int) $minute << 5) |
((int) $second >> 1);
}
}
9 changes: 9 additions & 0 deletions test/TimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ public function testNormalDateToDosTime(): void
Time::dateTimeToDosTime(new DateTimeImmutable('1980-01-01T00:00:00+00:00')),
2162688
);

// Local timezone different than UTC.
$prevLocalTimezone = date_default_timezone_get();
date_default_timezone_set('Europe/Berlin');
$this->assertSame(
Time::dateTimeToDosTime(new DateTimeImmutable('1980-01-01T00:00:00+00:00')),
2162688
);
date_default_timezone_set($prevLocalTimezone);
}

public function testTooEarlyDateToDosTime(): void
Expand Down

0 comments on commit 9da34d6

Please sign in to comment.