Skip to content

02: Elapsed Time with Time\Duration

Build a retry-delay calculator using seconds and milliseconds. A duration measures an amount of elapsed time and carries no calendar date or time zone.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable duration.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/02-duration/duration.php
duration.php
<?php
declare(strict_types=1);
use Time\Duration;
$baseDelay = Duration::fromMilliseconds(750);
$attemptDelay = $baseDelay->multiplyBy(3);
$delay = min($attemptDelay, Duration::fromSeconds(2));
printf("Base: %d s %d ns\n", $baseDelay->seconds, $baseDelay->nanoseconds);
printf("Capped delay: %d s %d ns\n", $delay->seconds, $delay->nanoseconds);
Base: 0 s 750000000 ns
Capped delay: 2 s 0 ns

Factories make the unit explicit. Arithmetic produces a new duration, so a shared base delay remains intact. The seconds and nanoseconds properties expose normalized components, and durations can be compared directly.

Calculate the delay for attempts zero through four with a cap of two seconds. Check that the final delay stays at the cap.

Continue with Wait for I/O with Io\Poll.