Epoch in PHP

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in PHP.

<?php

// Use time() to get the current Unix timestamp (seconds since the epoch)
$now = time();
echo date('Y-m-d H:i:s', $now) . " UTC\n";

// Seconds since the epoch
echo $now . "\n";

// Milliseconds since the epoch
echo (int)($now * 1000) . "\n";

// Microseconds since the epoch
echo (int)($now * 1000000) . "\n";

// Convert seconds since the epoch back to a DateTime object
$dateTime = new DateTime("@$now");
echo $dateTime->format('Y-m-d H:i:s') . " UTC\n";

// Convert microseconds since the epoch to a DateTime object
$microseconds = $now * 1000000;
$dateTime = DateTime::createFromFormat('U.u', sprintf('%.6F', $microseconds / 1000000));
echo $dateTime->format('Y-m-d H:i:s.u') . " UTC\n";

To run the program, save it as epoch.php and use the PHP interpreter:

$ php epoch.php
2023-06-01 12:34:56 UTC
1685623496
1685623496000
1685623496000000
2023-06-01 12:34:56 UTC
2023-06-01 12:34:56.000000 UTC

In PHP, we use the time() function to get the current Unix timestamp in seconds. For milliseconds and microseconds, we multiply the timestamp by 1000 and 1000000 respectively.

To convert a Unix timestamp back to a readable date and time, we can use the DateTime class or the date() function.

PHP doesn’t have a built-in function for nanoseconds precision, so we’ve used microseconds (millionths of a second) as the highest precision available.

Next, we’ll look at another time-related task: time parsing and formatting in PHP.