Current Location: Home> Latest Articles> PHP Timestamp to Date Format Tutorial - date() Function Explained

PHP Timestamp to Date Format Tutorial - date() Function Explained

M66 2025-07-08

How to Convert Timestamp to Date Format in PHP

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().

Using the date() Function

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:

  • format: Specifies the output date format.
  • timestamp: The timestamp to convert, defaulting to the current time.

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

Predefined Format Strings

PHP offers several predefined format strings for dates, including the following:

  • Y: Four-digit year
  • y: Two-digit year
  • m: Two-digit month
  • d: Two-digit day
  • H: Hour (24-hour format)
  • i: Minute
  • s: Second
  • a: AM/PM marker

Practical Example

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

Using the strtotime() Function

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.

Conclusion

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.