Skip to content

Core\Time\Duration::toMilliseconds

$duration->toMilliseconds(): int

Returns the length of a duration as a number of whole milliseconds. A millisecond is one thousandth of a second.

Use it when another program expects milliseconds. Many do: a timer in a browser script, a field in a JSON reply, or the retry time of an event stream. The method counts only whole milliseconds. The part that is shorter than one millisecond is ignored, so 999 microseconds gives 0. A negative duration gives a negative number in the same way. Every duration fits, so this method never throws.

Use toNanoseconds when you need the exact length.

Return value

Returns int. The nanosecond count divided by 1 000 000, truncated toward zero.

Examples

Read whole milliseconds

<?nvs
// Shows how to read the length of a duration as a number of milliseconds.
Core\Time\Duration $wait = 1s500ms;
// This prints 1500.
echo $wait->toMilliseconds(), "\n";
// A negative duration gives a negative number. This prints -2000.
Core\Time\Duration $back = 2s;
echo $back->negated()->toMilliseconds(), "\n";
Output
1500
-2000

Only whole milliseconds

<?nvs
// Shows that `toMilliseconds` counts only whole milliseconds.
// 999 microseconds is shorter than one millisecond. This prints 0.
echo Core\Time\Duration::microseconds(999)->toMilliseconds(), "\n";
// 2500 microseconds is 2 whole milliseconds and 500 microseconds more. This prints 2.
echo Core\Time\Duration::microseconds(2500)->toMilliseconds(), "\n";
// The same is true below zero. This prints -2.
echo Core\Time\Duration::microseconds(-2500)->toMilliseconds(), "\n";
Output
0
2
-2

Tell a browser when to retry

<?nvs
// Writes a JSON reply that tells a browser script how long to wait before it tries again.
// Each failed attempt doubles the wait. After three failed attempts, the wait is 16 seconds.
Core\Time\Duration $wait = 2s;
int $failed = 3;
int $i = 0;
while ($i < $failed) {
$wait = $wait->multipliedBy(2);
$i = $i + 1;
}
// A browser timer counts in milliseconds. This prints {"retryAfterMs":16000}.
echo "{\"retryAfterMs\":", $wait->toMilliseconds(), "}\n";
Output
{"retryAfterMs":16000}