Skip to content

Core\Time\Duration::minus

Returns a new duration that is the duration you call it on, with another duration taken away. The duration you call it on does not change.

Use it to find what is left of a length, for example the working time of a shift without its break, or the time a request still has before its limit. When the duration you take away is longer, the result is negative. Taking away a negative duration makes the result longer.

The result must fit in a duration, which is about 292 years in each direction. A difference that is longer throws a RuntimeError.

Parameters

  • $dCore\Time\DurationThe duration to subtract; a negative one lengthens the result.

Return value

Returns Core\Time\Duration. A new Duration of the difference, negative where $d is the longer; the receiver is unchanged.

Errors

  • RuntimeErrorThe difference is longer than a Duration can hold.

Examples

Take a break off

<?nvs
// Shows how to subtract one duration from another.
Core\Time\Duration $shift = 8h;
// A shift of 8 hours with a 45 minute break has 7 hours 15 minutes of work. This prints 7h15m.
echo $shift->minus(45m)->toString(), "\n";
// `$shift` itself does not change. This prints 8h.
echo $shift->toString(), "\n";
// A longer duration taken from a shorter one gives a negative duration. This prints -30m.
echo 15m->minus(45m)->toString(), "\n";
Output
7h15m
8h
-30m

Past the smallest duration

<?nvs
// Shows what happens when a difference is too long for a duration.
Core\Time\Duration $smallest = Core\Time\Duration::nanoseconds(-9223372036854775807 - 1);
// Taking away a negative duration makes the result longer. This prints -9223372036854775807.
echo $smallest->minus(Core\Time\Duration::nanoseconds(-1))->toNanoseconds(), "\n";
// Nothing is smaller than the smallest duration. Taking away one more nanosecond throws a `RuntimeError`.
try {
$smallest->minus(Core\Time\Duration::nanoseconds(1));
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
-9223372036854775807
Core\Time\Duration::minus(): this duration is longer than `Core\Time\Duration` can hold

Time left for a request

<?nvs
// Tracks how much time a request has left, when it may take 2 seconds in total.
Core\Time\Duration $left = 2s;
array<int> $steps = [350, 900, 480];
// Each step takes some milliseconds away. This prints 1s650ms, 750ms and 270ms.
foreach ($steps as int $ms) {
$left = $left->minus(Core\Time\Duration::milliseconds($ms));
echo $left->toString(), "\n";
}
Output
1s650ms
750ms
270ms