In PHP, a timestamp is the number of seconds that have passed since January 1, 1970, 00:00:00 UTC. To convert a timestamp to a human-readable date format, the most commonly used function is date().
The date() function is the most common method for converting a timestamp to a date format. Its basic syntax is as follows:
<span class="fun">date(format, timestamp)</span>
Where:
For example, the following code converts the timestamp to a “year-month-day” format:
$timestamp = time();
$date = date("Y-m-d", $timestamp);
echo $date; // Output: 2023-03-08
PHP offers several predefined format strings for dates, including the following:
Suppose you have a timestamp stored in a database, and you want to display it on a webpage in the format “Weekday, Year-Month-Day.” The following code will do that:
$timestamp = strtotime("2023-03-08 12:30:00");
$weekday = date("l", $timestamp);
$date = date("Y-m-d", $timestamp);
echo "$weekday, $date"; // Output: Wednesday, 2023-03-08
The strtotime() function is used to convert a human-readable date/time string into a timestamp. It complements the date() function and makes it easy to convert between dates and timestamps in your application.
With the examples in this article, you can easily use the date() function to convert PHP timestamps into various date formats. Additionally, by combining it with the strtotime() function, you can effortlessly handle different date and time conversions in your programming tasks.