Get timestamp in seconds in PHP
This article demonstrates how to get the current Unix timestamp in seconds in PHP.
1. Using time() function
You can use the time() function to obtain the current Unix timestamp in seconds. It is equivalent to the number of seconds elapsed since the Unix epoch (January 1, 1970 GMT).
|
1 2 3 4 |
<?php $timestamp = time(); echo $timestamp; ?> |
To get the timestamp of the start of the request instead of the current time, consider using the $_SERVER['REQUEST_TIME'] variable.
|
1 2 3 4 |
<?php $timestamp = $_SERVER['REQUEST_TIME']; echo $timestamp; ?> |
2. Using gettimeofday() function
Another alternative to getting the current time is using the gettimeofday() function, which returns an array with 'sec', 'usec', 'minuteswest', and 'dsttime' as keys. To get the elapsed seconds since the Unix epoch, you can use the value corresponding to the 'sec' key from the returned array.
|
1 2 3 4 5 |
<?php $timeofday = gettimeofday(); $timestamp = $timeofday["sec"]; echo $timestamp; ?> |
The gettimeofday() function optionally takes the boolean value true, which makes the function return a float value rather than a string. To get the integer timestamp in seconds, you can always round down the value using the floor() function.
|
1 2 3 4 |
<?php $timestamp = floor(gettimeofday(true)); echo $timestamp; ?> |
3. Using DateTime::format() function
Finally, you can use the object-oriented function DateTime::format() for formatting a date according to the given format. To obtain the number of seconds since the Unix epoch, you can format the date using the U parameter.
|
1 2 3 4 |
<?php $timestamp = (new DateTime)->format('U'); echo $timestamp; ?> |
Alternatively, you can use the procedural function date_format() to obtain the number of seconds since the Unix epoch with the U format parameter.
|
1 2 3 4 5 6 7 8 |
<?php $date = '2017/10/31 16:25:00'; $dateTime = date_create($date); $timestamp = date_format($dateTime, 'U'); echo $timestamp; // 1509463500 ?> |
That’s all there is to getting the current Unix timestamp in seconds in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)