Skip to content

Core\Time\Duration::plus

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

Use it to add lengths of time together, for example the steps of a job, or a delay that grows each time a request is tried again. Adding a negative duration makes the result shorter, and the result can be negative.

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

Parameters

  • $dCore\Time\DurationThe duration to add; a negative one shortens the result.

Return value

Returns Core\Time\Duration. A new Duration of the sum; the receiver is unchanged.

Errors

  • RuntimeErrorThe sum is longer than a Duration can hold.

Examples

Add two lengths

<?nvs
// Shows how to add one duration to another.
Core\Time\Duration $film = 1h45m;
// A film of 1 hour 45 minutes with 20 minutes of adverts takes 2 hours 5 minutes. This prints 2h5m.
echo $film->plus(20m)->toString(), "\n";
// `$film` itself does not change. This prints 1h45m.
echo $film->toString(), "\n";
// Adding a negative duration makes the result shorter. This prints 1h30m.
echo $film->plus(15m->negated())->toString(), "\n";
Output
2h5m
1h45m
1h30m

Past the largest duration

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

Waits between retries

<?nvs
// Adds up the waits of a program that tries a request again, and waits twice as long each time.
Core\Time\Duration $wait = 200ms;
Core\Time\Duration $waited = 0s;
// This prints the total after each wait: 200ms, 600ms, 1s400ms and 3s.
int $attempt = 1;
while ($attempt <= 4) {
$waited = $waited->plus($wait);
echo $waited->toString(), "\n";
$wait = $wait->multipliedBy(2);
$attempt = $attempt + 1;
}
Output
200ms
600ms
1s400ms
3s