Core\Time\Duration::negated
$duration->negated(): Core\Time\DurationReturns a duration of the same length that points the other way. A positive duration becomes negative, a negative one becomes positive, and zero stays zero. The duration you call it on does not change.
Use it to undo a step, for example to move a time back by an offset that you stored as a positive duration.
One duration has no opposite: the smallest one, Core\Time\Duration::nanoseconds of the smallest int. It is one nanosecond longer than the largest positive duration. For this duration, negated throws a RuntimeError. Every other duration can be negated.
Return value
Returns Core\Time\Duration. A new Duration of the same length in the opposite direction; the receiver is unchanged.
Errors
RuntimeErrorThe receiver is exactly −2⁶³ nanoseconds. This is the one duration whose negation does not fit.
Examples
Turn a duration around
<?nvs// Shows how to get the opposite of a duration: the same length, pointing the other way.
Core\Time\Duration $shift = 1h30m;
// `negated` returns a new duration. This prints -1h30m.echo $shift->negated()->toString(), "\n";
// `$shift` itself does not change. This prints 1h30m.echo $shift->toString(), "\n";
// Negating twice gives the first length again. This prints 5400.echo $shift->negated()->negated()->toSeconds(), "\n";-1h30m1h30m5400The one duration without an opposite
<?nvs// Shows the one duration that `negated` cannot turn around.
// The largest duration has an opposite. This prints -9223372036854775807.echo Core\Time\Duration::nanoseconds(9223372036854775807)->negated()->toNanoseconds(), "\n";
// The smallest duration is one nanosecond longer than the largest one.// Its opposite does not fit, so `negated` throws a `RuntimeError`.try { Core\Time\Duration::nanoseconds(-9223372036854775807 - 1)->negated();} catch (RuntimeError $e) { echo $e->message, "\n";}-9223372036854775807Core\Time\Duration::negated(): this duration is longer than `Core\Time\Duration` can holdCorrect a clock that runs ahead
<?nvs// Corrects the times that a device reports, when the clock of the device runs 90 seconds ahead.
Core\Time\Duration $ahead = 90s;array<string> $reported = ['2024-06-10T09:01:30Z', '2024-06-10T12:00:00Z'];
// Adding the negated offset moves each time 90 seconds back.// This prints 09:00:00 and 11:58:30 in full.foreach ($reported as string $time) { echo Core\Time\Instant::fromIso($time)->plus($ahead->negated())->toIso(), "\n";}2024-06-10T09:00:00Z2024-06-10T11:58:30Z