Core\Time\Duration::toNanoseconds
$duration->toNanoseconds(): intReturns the length of a duration as a number of nanoseconds. A nanosecond is one billionth of a second. A duration stores its length in nanoseconds, so this number is exact and no part of the length is lost.
Use it when you need the most precise number, for example to save a duration in a database column or to compare it with a timer that counts in nanoseconds. A negative duration gives a negative number. Every duration fits in an int, so this method never throws.
toMicroseconds, toMilliseconds and toSeconds return coarser numbers. They count only whole units and ignore the rest.
Return value
Returns int. The whole count of nanoseconds; negative for a duration that runs backwards.
Examples
Read the exact length
<?nvs// Shows how to read the length of a duration as a number of nanoseconds.
Core\Time\Duration $wait = 1500ms;// 1.5 seconds is 1500000000 nanoseconds. This prints 1500000000.echo $wait->toNanoseconds(), "\n";
// A negative duration gives a negative number. This prints -250.Core\Time\Duration $back = 250ns;echo $back->negated()->toNanoseconds(), "\n";1500000000-250Nothing is lost
<?nvs// Shows that `toNanoseconds` keeps every part of a duration.
Core\Time\Duration $step = 1s;$step = $step->plus(1ns);// This prints 1000000001. The last nanosecond is still there.echo $step->toNanoseconds(), "\n";// `toSeconds` counts only whole seconds. This prints 1.echo $step->toSeconds(), "\n";
// The longest duration is about 292 years. It still fits in an `int`.// This prints 9223372036854775807.echo Core\Time\Duration::nanoseconds(9223372036854775807)->toNanoseconds(), "\n";100000000119223372036854775807Save a duration as a number
<?nvs// Saves a duration as a number, for example in a database column, and reads it back later.
Core\Time\Duration $timeout = 2m30s;// A database column has no duration type, so the program saves the number of nanoseconds.// This prints 150000000000.string $saved = $timeout->toNanoseconds() as string;echo $saved, "\n";
// Later, the program reads the text and creates the same duration again. This prints 2m30s.?int $count = $saved as ?int;if ($count != null) { echo Core\Time\Duration::nanoseconds($count)->toString(), "\n";}1500000000002m30s