Core\Time\Instant::toEpochMicros
$instant->toEpochMicros(): intReturns the number of whole microseconds since 1 January 1970 at midnight UTC. A microsecond is one millionth of a second.
The result is an exact int. A moment before 1970 gives a negative number. The part of a microsecond is rounded down, to the earlier microsecond. So half a microsecond before 1970 gives -1.
Log tools and some databases store time in microseconds. Every instant has a microsecond count that fits in an int, so toEpochMicros never throws an error.
Return value
Returns int. An int, negative before 1970. The part of a microsecond is rounded down, to the earlier microsecond. Half a microsecond before 1970 gives -1. The count of every instant fits in an int.
Changelog
| Version | Change |
|---|---|
0.0.6 | toEpochSeconds, toEpochMillis and toEpochMicros return the time since 1 January 1970, rounded down to the earlier whole unit. For example, the instant half a second before 1970 gives -1 seconds. Instant::fromEpoch with the result and the remaining part gives the same instant. |
Examples
Microseconds since 1970
<?nvs// Shows how to get the microseconds since 1 January 1970 in UTC.
Core\Time\Instant $at = Core\Time\Instant::fromIso('2024-03-01T12:00:00.000123Z');
// This prints 1709294400000123. The last six digits are the 123 microseconds.echo $at->toEpochMicros(), "\n";1709294400000123Before 1970 the number is negative
<?nvs// Shows that a moment before 1970 gives a negative number.
// This is one microsecond before 1 January 1970, so this prints -1.echo Core\Time\Instant::fromIso('1969-12-31T23:59:59.999999Z')->toEpochMicros(), "\n";
// This prints -86400000000: one day before 1970, in microseconds.echo Core\Time\Instant::fromIso('1969-12-31T00:00:00Z')->toEpochMicros(), "\n";-1-86400000000A time column for log lines
<?nvs// Writes log lines that start with the time in microseconds, as many log tools expect.
array<string> $requests = [ '2024-03-01T12:00:00.000125Z' => 'GET /orders', '2024-03-01T12:00:00.000981Z' => 'POST /orders',];
foreach ($requests as string $at => string $request) { echo Core\Time\Instant::fromIso($at)->toEpochMicros(), ' ', $request, "\n";}// The two requests are 856 microseconds apart. A number in seconds or milliseconds would not show that.1709294400000125 GET /orders1709294400000981 POST /orders