Timestamps are important when you need to track changes and events. In PHP, you can easily obtain the current timestamp using the time() function. In this blog post, we’ll discuss how to get the current timestamp in PHP and how to format it for human-readable presentation.
Using the time() function
The simplest way to get the current timestamp in PHP is by using the time() function. This function returns the current Unix timestamp, which represents the number of seconds elapsed since January 1, 1970, at 00:00:00 GMT.
To get the current timestamp, simply call the function:
$current_timestamp = time(); echo $current_timestamp;
This will output the current Unix timestamp, for example 1634757935.
Formatting the timestamp
While the Unix timestamp is useful for calculations, it’s not very human-readable. To convert the timestamp into a more readable format, you can use the date() function. This function takes two arguments: a format string and the timestamp to be formatted.
For example, to display the current timestamp in the format “Y-m-d H:i:s”, use the following code:
$readable_timestamp = date("Y-m-d H:i:s", $current_timestamp); echo $readable_timestamp;
This will output a nicely formatted timestamp, for example 2021-10-20 12:38:55.
Using the DateTime class
Another way to work with timestamps in PHP is by using the DateTime class. This class provides an object-oriented way to manage dates and times, and offers many useful methods for manipulating and formatting them.
To get the current timestamp using the DateTime class, create a new DateTime object with no arguments:
$now = new DateTime(); echo $now->getTimestamp();
Just like with the time() function, this will output the current Unix timestamp. To format the DateTime object, you can use the format() method:
$readable_timestamp = $now->format("Y-m-d H:i:s"); echo $readable_timestamp;
Again, this will output a human-readable timestamp, for example 2021-10-20 12:38:55.
Conclusion
In this blog post, we’ve discussed how to get the current timestamp in PHP using both the time() function and the DateTime class. We’ve also shown how to format the timestamp for human-readable presentation using the date() function and the format() method of the DateTime class. With these tools at your disposal, you can easily track and display timestamps in your PHP applications.