Skip to content

Core\Time\Duration::seconds

Creates a duration of a given number of seconds.

Use it when the number of seconds is known only while the program runs, for example when a cache lifetime or a timeout comes from a setting, or from another service. When the number is fixed, write the duration directly in the code, such as 30s. A negative number gives a negative duration. The number can be up to 9,223,372,036 seconds, which is about 292 years. A larger number throws a RuntimeError.

toString shows the duration in the largest units that fit. So 90 seconds prints as 1m30s.

Parameters

  • $nintThe count of seconds; negative for a duration that runs backwards.

Return value

Returns Core\Time\Duration. A Duration of $n seconds.

Errors

  • RuntimeError$n seconds is longer than a Duration can hold — past ±2⁶³ nanoseconds, about 292 years.

Examples

A number of seconds

<?nvs
// Shows how to create a duration from a number of seconds.
int $count = 90;
Core\Time\Duration $pause = Core\Time\Duration::seconds($count);
// This prints 1m30s and 90000.
echo $pause->toString(), "\n";
echo $pause->toMilliseconds(), "\n";
// A negative number gives a negative duration. This prints -45s.
echo Core\Time\Duration::seconds(-45)->toString(), "\n";
Output
1m30s
90000
-45s

Too many seconds

<?nvs
// Shows the largest number of seconds a duration can have.
// This is the largest number that fits. This prints 15250w1d23h47m16s.
echo Core\Time\Duration::seconds(9223372036)->toString(), "\n";
// One more second does not fit, so `seconds` throws a `RuntimeError`.
int $tooMany = 9223372037;
try {
Core\Time\Duration::seconds($tooMany);
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
15250w1d23h47m16s
Core\Time\Duration::seconds(): this duration is longer than `Core\Time\Duration` can hold

Cache lifetime from a reply

<?nvs
// Turns the `max-age` value of a `Cache-Control` header into a duration, to know how long to keep a reply.
array<string> $headers = ['max-age=3600', 'max-age=86400', 'no-store'];
// `max-age` is a number of seconds. This prints 1h for 3600, 1d for 86400 and 0s for `no-store`.
foreach ($headers as string $header) {
Core\Time\Duration $keep = 0s;
// `Core\Str::afterPrefix` returns the text after `max-age=`. For `no-store`, the result is `null`.
?string $value = Core\Str::afterPrefix($header, 'max-age=');
if ($value != null) {
// `as ?int` converts the text to a whole number. If that is not possible, the result is `null`.
?int $count = $value as ?int;
if ($count != null) {
$keep = Core\Time\Duration::seconds($count);
}
}
echo $keep->toString(), "\n";
}
Output
1h
1d
0s