Skip to content

Core\Time\Instant::since

Returns the exact time between an earlier instant and this one, as a Duration.

$end->since($start) is how long it took to get from $start to $end. The result is an exact number of nanoseconds. It has no months or days of different lengths, so it is the same number wherever you run the program. When the argument is after this instant, the result is negative. So $start->plus($end->since($start)) is always $end again.

A Duration can be at most about 292 years long. When the two instants are further apart than that, since throws a RuntimeError.

To count calendar days or months between two dates, use a DateTime in a time zone instead.

Parameters

  • $earlierCore\Time\InstantThe instant to measure from.

Return value

Returns Core\Time\Duration. A Duration. It is negative when $earlier is after this instant.

Errors

  • RuntimeErrorThe two instants are more than about 292 years apart. That is the longest Duration there is.

Examples

How long a task took

<?nvs
// Shows how to measure the time between two instants.
Core\Time\Instant $start = Core\Time\Instant::fromIso('2024-03-01T09:00:00Z');
Core\Time\Instant $end = Core\Time\Instant::fromIso('2024-03-01T09:01:30.250Z');
// `since` returns a `Duration`. This prints 1m30s250ms.
Core\Time\Duration $took = $end->since($start);
echo $took->toString(), "\n";
// The same duration as a number of whole seconds. This prints 90.
echo $took->toSeconds(), "\n";
Output
1m30s250ms
90

A later argument is negative

<?nvs
// Shows that the result is negative when the argument is the later instant.
Core\Time\Instant $noon = Core\Time\Instant::fromIso('2024-03-01T12:00:00Z');
Core\Time\Instant $two = Core\Time\Instant::fromIso('2024-03-01T14:00:00Z');
// This prints 7200 and then -7200.
echo $two->since($noon)->toSeconds(), "\n";
echo $noon->since($two)->toSeconds(), "\n";
// `$two` plus the result is `$noon` again. This prints 2024-03-01T12:00:00Z.
echo $two->plus($noon->since($two))->toIso(), "\n";
Output
7200
-7200
2024-03-01T12:00:00Z

Find the slow requests

<?nvs
// Finds the requests in a log that took longer than half a second.
array<array<string>> $log = [
['/home', '2024-03-01T09:00:00.100Z', '2024-03-01T09:00:00.180Z'],
['/search', '2024-03-01T09:00:01.000Z', '2024-03-01T09:00:01.750Z'],
['/cart', '2024-03-01T09:00:02.000Z', '2024-03-01T09:00:02.500Z'],
];
foreach ($log as array<string> $request) {
Core\Time\Duration $took = Core\Time\Instant::fromIso($request[2])->since(Core\Time\Instant::fromIso($request[1]));
// Durations can be compared with `>`. This prints only /search 750ms.
if ($took > 500ms) {
echo $request[0], ' ', $took->toString(), "\n";
}
}
Output
/search 750ms