Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating DateTime from timestamp in PHP < 5.3

How do you create a DateTime from timestamp in versions less than < 5.3?

In 5.3 it would be:

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

The DateTime constructor wants a string, but this didn't work for me

$date = new DateTime("@$timeStamp"); 
like image 885
Yarin Avatar asked Dec 01 '10 22:12

Yarin


2 Answers

PHP 5 >= 5.3.0

$date = new DateTime(); $date->setTimestamp($timeStamp); 

Edit: Added correct PHP version for setTimestamp

like image 60
Dawid Ohia Avatar answered Sep 26 '22 05:09

Dawid Ohia


Assuming you want the date and the time and not just the date as in the previous answer:

$dtStr = date("c", $timeStamp); $date = new DateTime($dtStr); 

Seems pretty silly to have to do that though.

like image 38
Barry Simpson Avatar answered Sep 26 '22 05:09

Barry Simpson