Get PHP Current Unix Timestamp as Integer
This article explains how to retrieve the current Unix timestamp as
an integer in PHP. You will learn about the most efficient built-in
functions, such as time() and the DateTime
class, to quickly obtain the current time in seconds since the Unix
Epoch (January 1 1970 00:00:00 GMT).
Using the time()
Function
The most straightforward and common method to get the current Unix
timestamp as an integer in PHP is by using the built-in
time() function. This function requires no arguments and
automatically returns the current timestamp as an integer.
$timestamp = time();
echo $timestamp; // Outputs: 1700000000 (example)
echo gettype($timestamp); // Outputs: integerUsing the DateTime
Class
For an object-oriented approach, you can use PHP’s native
DateTime class. This method is highly readable and useful
if you are already working with date and time objects in your
application. The getTimestamp() method of the
DateTime object returns the Unix timestamp as an
integer.
$date = new DateTime();
$timestamp = $date->getTimestamp();
echo $timestamp; // Outputs the current Unix timestamp
echo gettype($timestamp); // Outputs: integerYou can also instantiate the class and call the method in a single line:
$timestamp = (new DateTime())->getTimestamp();Using
microtime() for Casted Integers
If you are working with high-precision time using
microtime(true) (which returns the current timestamp with
microseconds as a float), you can explicitly cast the float to an
integer to get the standard Unix timestamp. Note that this will discard
the microseconds.
$timestamp = (int) microtime(true);
echo $timestamp; // Outputs the current Unix timestamp as an integer