Skip to content

Core\Time\Duration::compareTo

$duration->compareTo(Core\Time\Duration $other): int$duration->compareTo(
    Core\Time\Duration $other,
): int

Compares this duration with another one and returns -1, 0 or 1.

The result is -1 when this duration is shorter, 0 when both have the same length, and 1 when this duration is longer. A negative duration is shorter than zero and shorter than every positive one.

You can also write <, >, <=, >= and <=> between two durations. They all use compareTo, so they always give the same answer.

Good to know: == compares two durations by their length too. 90m == 1h30m is true.

Parameters

  • $otherCore\Time\DurationThe duration to compare against.

Return value

Returns int. -1 when the receiver is shorter than $other, 0 when they are equal, 1 when it is longer.

Changelog

VersionChange
0.0.6== and != now compare a Date, TimeOfDay, Instant, Duration, Zone or DateTime by its value, so 90m == 1h30m is true. Two DateTime values are equal when they name the same moment, even in different time zones. Objects of every other class are still equal only when they are the same object.

Examples

Shorter equal longer

<?nvs
// Shows the three results of `compareTo` for a shorter, an equal and a longer duration.
Core\Time\Duration $break = 15m;
// This prints -1, because 10 minutes is shorter than 15 minutes.
echo 10m->compareTo($break), "\n";
// This prints 0. A quarter of an hour is the same length as 15 minutes.
echo Core\Time\Duration::seconds(900)->compareTo($break), "\n";
// This prints 1, because half an hour is longer.
echo 30m->compareTo($break), "\n";
// A negative duration is shorter than zero. This prints -1.
echo 5m->negated()->compareTo(Core\Time\Duration::seconds(0)), "\n";
Output
-1
0
1
-1

The same length written two ways

<?nvs
// Shows how to test whether two durations have the same length.
Core\Time\Duration $planned = 90m;
Core\Time\Duration $actual = 1h30m;
// `==` compares the length. 90 minutes is one hour and 30 minutes, so this prints "same".
echo $planned == $actual ? 'same' : 'different', "\n";
// `compareTo` returns 0 for the same length. This prints 0.
echo $planned->compareTo($actual), "\n";
// `<` and `>` use `compareTo` too. This prints "no".
echo $planned < $actual ? 'yes' : 'no', "\n";
Output
same
0
no

Find the slow requests

<?nvs
// Checks how long each request took against a time limit, and reports the slow ones.
Core\Time\Duration $limit = 250ms;
array<int> $timings = ['/home' => 120, '/search' => 250, '/report' => 1400, '/login' => 90];
foreach ($timings as string $path => int $ms) {
Core\Time\Duration $took = Core\Time\Duration::milliseconds($ms);
// `compareTo` returns 1 when the request took longer than the limit.
if ($took->compareTo($limit) == 1) {
echo 'slow: ', $path, ' took ', $took->toString(), "\n";
}
}
// This prints one line, for "/report". "/search" took exactly 250 ms, which is not slower than the limit.
Output
slow: /report took 1s400ms