How to Format Unix Timestamp to Date in PHP
Working with time in PHP often involves handling Unix timestamps,
which represent the number of seconds that have elapsed since January 1,
1970 (UTC). This article provides a quick, practical guide on how to
convert these integer timestamps into human-readable date and time
strings using PHP’s built-in date() function and the
object-oriented DateTime class.
Method 1: Using the
date() Function
The simplest and most common way to format a Unix timestamp in PHP is
by using the procedural date() function. This function
takes a format string as the first argument and the timestamp as the
optional second argument. If the timestamp is omitted, it defaults to
the current local time.
<?php
// Example Unix timestamp (October 31, 2023, 12:00:00 UTC)
$timestamp = 1698753600;
// Format the timestamp into Year-Month-Day Hour:Minute:Second
$readableDate = date("Y-m-d H:i:s", $timestamp);
echo $readableDate;
// Output: 2023-10-31 12:00:00 (depending on your server's default timezone)
?>Method 2: Using the
DateTime Class
For a modern, object-oriented approach that offers better timezone
handling, use PHP’s DateTime class. You can instantiate a
DateTime object and set the timestamp using the
setTimestamp() method.
<?php
$timestamp = 1698753600;
$date = new DateTime();
$date->setTimestamp($timestamp);
// Format the date
echo $date->format('Y-m-d H:i:s');
// Output: 2023-10-31 12:00:00
?>Alternatively, you can pass the timestamp directly to the constructor
by prefixing it with an @ symbol. Note that using the
@ syntax automatically sets the timezone to UTC.
<?php
$timestamp = 1698753600;
$date = new DateTime("@$timestamp");
echo $date->format('l, F j, Yg:i A');
// Output: Tuesday, October 31, 2023 12:00 PM
?>Handling Timezones
By default, the date() function uses the default
timezone set in your PHP configuration (php.ini). If you
need to output the date in a specific timezone, the
DateTime class makes it easy to convert:
<?php
$timestamp = 1698753600;
$date = new DateTime();
$date->setTimestamp($timestamp);
// Change timezone to New York
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format('Y-m-d H:i:s T');
// Output: 2023-10-31 08:00:00 EDT
?>Common Format Characters
Y: 4-digit year (e.g., 2023)m: Month with leading zeros (01 to 12)d: Day of the month with leading zeros (01 to 31)H: 24-hour format of an hour (00 to 23)i: Minutes with leading zeros (00 to 59)s: Seconds with leading zeros (00 to 59)l: Full text representation of the day of the week (e.g., Monday)F: Full text representation of a month (e.g., October)