Skip to content

Core\Time\TimeOfDay::compareTo

$timeOfDay->compareTo(Core\Time\TimeOfDay $other): int$timeOfDay->compareTo(
    Core\Time\TimeOfDay $other,
): int

Checks which of two times of day comes first, and returns -1, 0 or 1.

The result is -1 when the time comes earlier in the day than the other one, 0 when both are the same time, and 1 when it comes later. The check uses every part of the time, down to the nanosecond. A TimeOfDay has no date, so 00:10 always comes before 23:50.

The operators <, >, <=, >= and <=> use compareTo too, so you can write $a < $b. == compares the time too. Two times with the same hour, minute, second and nanosecond are equal, even when your program made them separately.

Parameters

  • $otherCore\Time\TimeOfDayThe time to compare against.

Return value

Returns int. -1 when this time is earlier in the day than $other, 0 when both are the same time, 1 when it is later.

Examples

Earlier or later

<?nvs
// Shows the three results of `compareTo`.
Core\Time\TimeOfDay $morning = Core\Time\TimeOfDay::at(9, 30);
Core\Time\TimeOfDay $evening = Core\Time\TimeOfDay::at(21, 30);
// This prints -1, then 1, then 0.
echo $morning->compareTo($evening), "\n";
echo $evening->compareTo($morning), "\n";
echo $morning->compareTo(Core\Time\TimeOfDay::at(9, 30)), "\n";
// `<` uses `compareTo`. This prints "morning first".
if ($morning < $evening) {
echo "morning first\n";
}
Output
-1
1
0
morning first

The same time twice

<?nvs
// Shows how to check if two times are the same time.
Core\Time\TimeOfDay $a = Core\Time\TimeOfDay::at(12, 0);
Core\Time\TimeOfDay $b = Core\Time\TimeOfDay::at(12, 0);
// `==` compares the time itself. Both are 12:00, so this prints "same time".
echo $a == $b ? 'same time' : 'different time', "\n";
// `compareTo` returns 0 for the same time. This prints 0.
echo $a->compareTo($b), "\n";
Output
same time
0

Is the shop open

<?nvs
// Checks if a shop is open at a given time of day.
Core\Time\TimeOfDay $opens = Core\Time\TimeOfDay::at(9, 0);
Core\Time\TimeOfDay $closes = Core\Time\TimeOfDay::at(18, 30);
array<Core\Time\TimeOfDay> $visits = [
Core\Time\TimeOfDay::at(8, 59),
Core\Time\TimeOfDay::at(9, 0),
Core\Time\TimeOfDay::at(18, 30),
];
// The shop is open from the opening time until just before the closing time.
// This prints closed, open and closed.
foreach ($visits as Core\Time\TimeOfDay $visit) {
bool $open = $visit->compareTo($opens) >= 0 && $visit->compareTo($closes) < 0;
echo $visit->format('HH:mm'), ' ', $open ? 'open' : 'closed', "\n";
}
Output
08:59 closed
09:00 open
18:30 closed