|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Stadly\Date; |
|
6
|
|
|
|
|
7
|
|
|
use DateInterval; |
|
8
|
|
|
|
|
9
|
|
|
final class Interval |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @param DateInterval $a First date interval to compare. |
|
13
|
|
|
* @param DateInterval $b Second date interval to compare. |
|
14
|
|
|
* @return int|null 0 if $a == $b, < 0 if $a < b, > 0 if $a > $b, null if undetermined. |
|
15
|
|
|
*/ |
|
16
|
36 |
|
public static function compare(DateInterval $a, DateInterval $b): ?int |
|
17
|
|
|
{ |
|
18
|
36 |
|
$aSeconds = self::getSecondsInInterval($a); |
|
19
|
36 |
|
$aMonths = self::getMonthsInInterval($a); |
|
20
|
36 |
|
$bSeconds = self::getSecondsInInterval($b); |
|
21
|
36 |
|
$bMonths = self::getMonthsInInterval($b); |
|
22
|
|
|
|
|
23
|
36 |
|
$minSecondsPerMonth = 28 * 24 * 60 * 60; |
|
24
|
36 |
|
$maxSecondsPerMonth = 31 * 24 * 60 * 60; |
|
25
|
|
|
|
|
26
|
36 |
|
if ($aSeconds === $bSeconds || $aMonths === $bMonths) { |
|
27
|
28 |
|
return $aSeconds + $aMonths <=> $bSeconds + $bMonths; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
8 |
|
if ($aSeconds + $maxSecondsPerMonth * $aMonths < $bSeconds + $minSecondsPerMonth * $bMonths) { |
|
31
|
2 |
|
return -1; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
6 |
|
if ($bSeconds + $maxSecondsPerMonth * $bMonths < $aSeconds + $minSecondsPerMonth * $aMonths) { |
|
35
|
2 |
|
return 1; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
4 |
|
return null; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param DateInterval $interval Date interval. |
|
43
|
|
|
* @return int Number of months in the date interval. |
|
44
|
|
|
*/ |
|
45
|
36 |
|
private static function getMonthsInInterval(DateInterval $interval): int |
|
46
|
|
|
{ |
|
47
|
36 |
|
$years = $interval->y * 12; |
|
48
|
36 |
|
$months = $years * 12 + $interval->m; |
|
49
|
|
|
|
|
50
|
36 |
|
if ($interval->invert === 1) { |
|
51
|
15 |
|
return -$months; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
23 |
|
return $months; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param DateInterval $interval Date interval. |
|
59
|
|
|
* @return float Number of seconds in the date interval. |
|
60
|
|
|
*/ |
|
61
|
36 |
|
private static function getSecondsInInterval(DateInterval $interval): float |
|
62
|
|
|
{ |
|
63
|
36 |
|
$days = $interval->d; |
|
64
|
36 |
|
$hours = $days * 24 + $interval->h; |
|
65
|
36 |
|
$minutes = $hours * 60 + $interval->i; |
|
66
|
36 |
|
$seconds = $minutes * 60 + $interval->s + $interval->f; |
|
67
|
|
|
|
|
68
|
36 |
|
if ($interval->invert === 1) { |
|
69
|
15 |
|
return -$seconds; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
23 |
|
return $seconds; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|