Skip to content

Core\Time\Duration::toSeconds

$duration->toSeconds(): int

Returns the length of a duration as a number of whole seconds.

Use it when a header, a setting or another service expects seconds. For example, the max-age value of a Cache-Control header and the Retry-After header are both numbers of seconds. The method counts only whole seconds. The part that is shorter than one second is ignored, so a duration of 999 milliseconds gives 0 and 1.5 seconds gives 1. A negative duration gives a negative number in the same way. Every duration fits, so this method never throws.

Use toMilliseconds or toNanoseconds when the part after the last whole second matters.

Return value

Returns int. The nanosecond count divided by 1 000 000 000, truncated toward zero — 0 for anything shorter than a second.

Examples

Read whole seconds

<?nvs
// Shows how to read the length of a duration as a number of seconds.
Core\Time\Duration $pause = 1m30s;
// This prints 90.
echo $pause->toSeconds(), "\n";
// This prints 7200.
Core\Time\Duration $shift = 2h;
echo $shift->toSeconds(), "\n";
// A negative duration gives a negative number. This prints -45.
echo Core\Time\Duration::seconds(-45)->toSeconds(), "\n";
Output
90
7200
-45

Shorter than a second

<?nvs
// Shows that `toSeconds` counts only whole seconds.
// 999 milliseconds is shorter than one second. This prints 0.
echo Core\Time\Duration::milliseconds(999)->toSeconds(), "\n";
// 1.5 seconds is 1 whole second and half a second more. This prints 1.
echo Core\Time\Duration::milliseconds(1500)->toSeconds(), "\n";
// The same is true below zero. This prints -1.
echo Core\Time\Duration::milliseconds(-1500)->toSeconds(), "\n";
Output
0
1
-1

A cache header

<?nvs
// Writes the `Cache-Control` header for pages that a browser may keep for different times.
array<Core\Time\Duration> $lifetimes = [90s, 1h, 1d];
// `max-age` is a number of seconds.
// This prints max-age=90, max-age=3600 and max-age=86400, one per line.
foreach ($lifetimes as Core\Time\Duration $keep) {
echo 'Cache-Control: max-age=', $keep->toSeconds(), "\n";
}
Output
Cache-Control: max-age=90
Cache-Control: max-age=3600
Cache-Control: max-age=86400