Skip to content

Core\Time\Duration::toString

$duration->toString(): string

Returns a duration as text, in the same syntax you use to write a duration in code, such as 1h30m or 250ms.

The largest unit comes first, and a unit with a count of zero is left out. So 90 seconds gives 1m30s, and 1.5 seconds gives 1s500ms. A duration of zero gives 0s. A negative duration gives the same text with a - in front, such as -1h. The method never throws.

Use it to show a duration to a person, or to write it to a log or a setting. Text from a duration that is not negative can be read back with Core\Time\Duration::parse, and the result is the same duration. parse throws an error for text that starts with -.

The examples show a few durations as text, a negative duration, and a log line that says how long a job took. A duration also becomes this text when you put it inside a string with "{$took}".

Return value

Returns string. The receiver written as a duration, such as 1h30m.

Examples

Durations as text

<?nvs
// Shows how a duration is written as text.
// The largest unit comes first. This prints 1m30s.
echo (90s)->toString(), "\n";
// A unit with a count of zero is left out. This prints 2h5s.
echo (2h)->plus(5s)->toString(), "\n";
// 1.5 seconds prints as 1s500ms.
echo (1500ms)->toString(), "\n";
// A duration of zero prints as 0s.
echo (0s)->toString(), "\n";
// Inside a string, a duration is written the same way. This prints "wait 1h30m".
Core\Time\Duration $wait = 90m;
echo "wait {$wait}\n";
Output
1m30s
2h5s
1s500ms
0s
wait 1h30m

A negative duration

<?nvs
// Shows how a negative duration is written as text, and how to read the text back.
// Two hours minus three hours is minus one hour. This prints -1h.
Core\Time\Duration $late = (2h)->minus(3h);
echo $late->toString(), "\n";
// Text from a duration that is not negative reads back with `parse`. This prints "same".
string $text = (1h30m)->toString();
echo Core\Time\Duration::parse($text)->compareTo(1h30m) == 0 ? 'same' : 'different', "\n";
// `parse` throws a `ParseError` for text that starts with `-`. This prints "cannot read -1h".
string $negative = $late->toString();
try {
Core\Time\Duration::parse($negative);
} catch (ParseError $e) {
echo 'cannot read ', $negative, "\n";
}
Output
-1h
same
cannot read -1h

Log how long a job took

<?nvs
// Writes a log line that says how long a job took.
var $started = Core\Time\Instant::fromIso('2024-05-01T09:00:00Z');
var $finished = Core\Time\Instant::fromIso('2024-05-01T09:02:05.250Z');
Core\Time\Duration $took = $finished->since($started);
// This prints "import finished in 2m5s250ms".
echo 'import finished in ', $took->toString(), "\n";
// A job that takes longer than its limit gets a warning. This prints "slow: 2m5s250ms is over 2m".
Core\Time\Duration $limit = 2m;
if ($took->compareTo($limit) > 0) {
echo 'slow: ', $took->toString(), ' is over ', $limit->toString(), "\n";
}
Output
import finished in 2m5s250ms
slow: 2m5s250ms is over 2m