php8.5
Home/ Manual/ time / duration/ Time\Duration::fromNanoseconds

Time\Duration::fromNanoseconds

PHP function Edit on GitHub ✎

(PHP 8 >= 8.6.0)

Creates a duration from a number of nanoseconds

Description

Time\Duration::fromNanoseconds(int $nanoseconds): Time\Duration

Creates a non-negative duration of nanoseconds nanoseconds. The value is normalized into whole seconds and nanoseconds, see the Time\Duration::$seconds and Time\Duration::$nanoseconds properties.

Parameters

nanoseconds

The number of nanoseconds. Must be greater than or equal to 0.

Return Values

Returns a new Time\Duration object.

Errors/Exceptions

  • If nanoseconds is negative, a ValueError is thrown.

Examples

Time\Duration::fromNanoseconds example

php
<?php
var_dump(\Time\Duration::fromNanoseconds(1_500_000_000));

The above example will output:

output
object(Time\Duration)#1 (3) {
  ["seconds"]=>
  int(1)
  ["nanoseconds"]=>
  int(500000000)
  ["negative"]=>
  bool(false)
}

Measuring elapsed time with hrtime()

php
<?php
$start = hrtime(true);
usleep(1000);
$elapsed = \Time\Duration::fromNanoseconds(hrtime(true) - $start);

var_dump($elapsed);

The above example will output something similar to:

output
object(Time\Duration)#1 (3) {
  ["seconds"]=>
  int(0)
  ["nanoseconds"]=>
  int(1062541)
  ["negative"]=>
  bool(false)
}

See Also

  • Time\Duration::fromSeconds
  • Time\Duration::fromMicroseconds
  • Time\Duration::fromMilliseconds
  • hrtime()

Source: reference/datetime/time/duration/fromnanoseconds.xml · from the official PHP manual (php/doc-en)