Core\Time\Instant::toEpochMillis
$instant->toEpochMillis(): intReturns the number of whole milliseconds since 1 January 1970 at midnight UTC. A millisecond is one thousandth of a second.
The result is an exact int. A moment before 1970 gives a negative number. The part of a millisecond is rounded down, to the earlier millisecond. So half a millisecond before 1970 gives -1.
JavaScript, many databases and many web APIs count time in milliseconds. Every instant has a millisecond count that fits in an int, so toEpochMillis never throws an error.
Return value
Returns int. An int, negative before 1970. The part of a millisecond is rounded down, to the earlier millisecond. Half a millisecond 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
Milliseconds since 1970
<?nvs// Shows how to get the milliseconds since 1 January 1970 in UTC.
Core\Time\Instant $start = Core\Time\Instant::fromIso('2024-03-01T12:00:00.250Z');
// This prints 1709294400250. The last three digits are the 250 milliseconds.echo $start->toEpochMillis(), "\n";1709294400250Smaller parts are dropped
<?nvs// Shows that `toEpochMillis` drops the part of a millisecond. It does not round.
Core\Time\Instant $at = Core\Time\Instant::fromIso('2024-03-01T12:00:00.250999Z');
// This prints 1709294400250. The last 0.999 milliseconds are dropped.echo $at->toEpochMillis(), "\n";1709294400250Points for a javascript chart
<?nvs// Builds the points of a chart for a web page. JavaScript counts time in milliseconds.
array<int> $visitors = [ '2024-03-01T12:00:00Z' => 12, '2024-03-01T12:05:00Z' => 19, '2024-03-01T12:10:00Z' => 7,];
foreach ($visitors as string $at => int $count) { echo '{x: ', Core\Time\Instant::fromIso($at)->toEpochMillis(), ', y: ', $count, "}\n";}// The browser reads each x with `new Date(x)`.{x: 1709294400000, y: 12}{x: 1709294700000, y: 19}{x: 1709295000000, y: 7}