Skip to content

Commit

Permalink
Better DateInterval encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Feb 4, 2025
1 parent 7ac4f6c commit 2f2d918
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Internal/Support/DateInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
*/
final class DateInterval
{
/** @deprecated Use days instead */
public const FORMAT_YEARS = 'years';
/** @deprecated Use days instead */
public const FORMAT_MONTHS = 'months';
public const FORMAT_WEEKS = 'weeks';
public const FORMAT_DAYS = 'days';
Expand Down Expand Up @@ -73,11 +75,17 @@ public static function parse($interval, string $format = self::FORMAT_MILLISECON
default => $fraction > 0 ? match ($format) {
self::FORMAT_SECONDS => $fraction * 1_000_000,
self::FORMAT_MINUTES => $fraction * 60_000_000,
self::FORMAT_HOURS => $fraction * 3_600_000_000,
self::FORMAT_DAYS => $fraction * 86_400_000_000,
self::FORMAT_WEEKS => $fraction * 604_800_000_000,
default => 0,
} : 0,
};
$micros = (int) \round($micros);
$seconds = (int) \floor($micros / 1_000_000);
$micros = $micros - ($seconds * 1_000_000);

$seconds = \floor($micros / 1_000_000) + \floor(match ($format) {
$seconds += \floor(match ($format) {
self::FORMAT_SECONDS => $int,
self::FORMAT_MINUTES => $int * 60,
self::FORMAT_HOURS => $int * 3600,
Expand All @@ -97,7 +105,7 @@ public static function parse($interval, string $format = self::FORMAT_MILLISECON
hours: $hours % 24,
minutes: $minutes % 60,
seconds: $seconds % 60,
microseconds: $micros % 1000_000,
microseconds: $micros,
);

case $interval instanceof Duration:
Expand Down
3 changes: 3 additions & 0 deletions tests/Unit/Internal/Support/DateIntervalTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,8 @@ public static function provideValuesToParse(): iterable
yield [1, DateInterval::FORMAT_HOURS, 3_600_000_000, '0/1/0/0'];
yield [1, DateInterval::FORMAT_DAYS, 86_400_000_000, '1/0/0/0'];
yield [1, DateInterval::FORMAT_WEEKS, 604_800_000_000, '7/0/0/0'];
yield [(0.1 + 0.7) * 10.0, DateInterval::FORMAT_SECONDS, 8_000_000, '0/0/0/8'];
yield [(0.1 + 0.7) * 10.0, DateInterval::FORMAT_DAYS, 691200000000, '8/0/0/0'];
yield [(0.1 + 0.7) * 10.0, DateInterval::FORMAT_WEEKS, 4838400000000, '56/0/0/0'];
}
}

0 comments on commit 2f2d918

Please sign in to comment.