0
0
PhpHow-ToBeginner · 2 min read

PHP How to Convert Timestamp to Date Easily

Use the date() function with a format string and the timestamp like date('Y-m-d H:i:s', $timestamp) to convert a timestamp to a date in PHP.
📋

Examples

Input0
Output1970-01-01 00:00:00
Input1686000000
Output2023-06-06 00:00:00
Input-1
Output1969-12-31 23:59:59
🧠

How to Think About It

To convert a timestamp to a date, think of the timestamp as the number of seconds since a fixed point in time (the Unix epoch). You use PHP's built-in functions to translate this number into a human-readable date format by specifying how you want the date to look.
📐

Algorithm

1
Get the timestamp value as input.
2
Choose the desired date format string (e.g., 'Y-m-d H:i:s').
3
Use PHP's date function with the format and timestamp to get the formatted date string.
4
Return or print the formatted date string.
💻

Code

php
<?php
$timestamp = 1686000000;
$formattedDate = date('Y-m-d H:i:s', $timestamp);
echo $formattedDate;
?>
Output
2023-06-06 00:00:00
🔍

Dry Run

Let's trace converting timestamp 1686000000 to a date string.

1

Input timestamp

timestamp = 1686000000

2

Call date function

date('Y-m-d H:i:s', 1686000000)

3

Get formatted date

formattedDate = '2023-06-06 00:00:00'

StepActionValue
1Input timestamp1686000000
2Format timestamp2023-06-06 00:00:00
💡

Why This Works

Step 1: Timestamp as seconds

The timestamp is the number of seconds since January 1, 1970 (Unix epoch).

Step 2: date() function

The date() function formats this number into a readable date string using the format you provide.

Step 3: Format string

The format string like 'Y-m-d H:i:s' tells PHP how to display year, month, day, hour, minute, and second.

🔄

Alternative Approaches

Using DateTime class
php
<?php
$timestamp = 1686000000;
$date = new DateTime();
$date->setTimestamp($timestamp);
echo $date->format('Y-m-d H:i:s');
?>
This method is object-oriented and useful for more complex date manipulations.
Using gmdate() for UTC time
php
<?php
$timestamp = 1686000000;
echo gmdate('Y-m-d H:i:s', $timestamp);
?>
Use <code>gmdate()</code> to get the date in UTC instead of local time.

Complexity: O(1) time, O(1) space

Time Complexity

Converting a timestamp to a date is a direct calculation with no loops, so it runs in constant time.

Space Complexity

Only a small fixed amount of memory is used to store the formatted string, so space is constant.

Which Approach is Fastest?

Using date() is slightly faster and simpler than DateTime, but DateTime offers more flexibility.

ApproachTimeSpaceBest For
date()O(1)O(1)Simple formatting, fastest
DateTime classO(1)O(1)Complex date operations, object-oriented
gmdate()O(1)O(1)UTC date formatting
💡
Always specify the date format string clearly to get the date in the style you want.
⚠️
Forgetting to pass the timestamp as the second argument to date() causes it to use the current time instead.