Skip to content

Core\Time\Instant::toEpochSeconds

$instant->toEpochSeconds(): int

Returns the Unix timestamp of this instant: the number of whole seconds since 1 January 1970 at midnight UTC.

The result is an int. A moment before 1970 gives a negative number. The part of a second is rounded down, to the earlier second. So half a second after 1970 gives 0, and half a second before 1970 gives -1. To get the same instant back, pass this number and the nanoseconds that were dropped to Core\Time\Instant::fromEpoch.

Every instant has a Unix timestamp, so toEpochSeconds never throws an error. Use toEpochMillis or toEpochMicros when you need the part of a second too.

Return value

Returns int. An int, negative before 1970. The part of a second is rounded down, to the earlier second. Half a second before 1970 gives -1.

Changelog

VersionChange
0.0.6toEpochSeconds, 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

A unix timestamp

<?nvs
// Shows how to get the Unix timestamp of a moment: the seconds since 1 January 1970 in UTC.
Core\Time\Instant $noon = Core\Time\Instant::fromIso('2024-03-01T12:00:00Z');
// This prints 1709294400.
echo $noon->toEpochSeconds(), "\n";
Output
1709294400

The part below a second is dropped

<?nvs
// Shows that `toEpochSeconds` rounds the part of a second down, to the earlier second.
// This prints 1709294400. The 0.9 seconds are dropped.
echo Core\Time\Instant::fromIso('2024-03-01T12:00:00.9Z')->toEpochSeconds(), "\n";
// Half a second before 1970 is -0.5 seconds. The earlier whole second is -1,
// so this prints -1.
echo Core\Time\Instant::fromIso('1969-12-31T23:59:59.5Z')->toEpochSeconds(), "\n";
Output
1709294400
-1

An expiry time for an api

<?nvs
// Builds the expiry time of a download link, for an API that wants a Unix timestamp.
// A real program uses `Core\Time::now()` here. A fixed time keeps the output the same.
Core\Time\Instant $now = Core\Time\Instant::fromIso('2024-03-01T12:00:00Z');
Core\Time\Instant $expires = $now->plus(15m);
echo 'https://files.example.com/report.pdf?expires=', $expires->toEpochSeconds(), "\n";
// This prints a link that ends with expires=1709295300.
Output
https://files.example.com/report.pdf?expires=1709295300