Convert timestamp to readable date/time PHP


I have a timestamp stored in a session (1299446702).

How can I convert that to a readable date/time in PHP? I have tried srttotime, etc. to no avail.

3/22/2011 11:42:41 AM

strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.

If you have a timestamp that you want to use (apparently you do), it is the second argument of date().


I just added H:i:s to Rocket's answer to get the time along with the date.

echo date('m/d/Y H:i:s', 1299446702);

Output: 03/06/2011 16:25:02


$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';

$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
echo $date->format($datetimeFormat);

result: 2016-06-07 14:29:00

Other time zones:


If you are using PHP date(), you can use this code to get the date, time, second, etc.

$time = time();               // you have 1299446702 in time
$year = $time/31556926 % 12;  // to get year
$week = $time / 604800 % 52;  // to get weeks
$hour = $time / 3600 % 24;    // to get hours
$minute = $time / 60 % 60;    // to get minutes
$second = $time % 60;         // to get seconds

I know that's an old one question, but its high in the search results.

If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:

$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);

Following @sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.

$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored

You may check PHP's manual for DateTime::createFromFormat for more info and options.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]