Creating DateTime from timestamp in PHP < 5.3

PhpDatetimeTimestampPhp 5.2

Php Problem Overview


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");

Php Solutions


Solution 1 - Php

PHP 5 >= 5.3.0

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

Edit: Added correct PHP version for setTimestamp

Solution 2 - Php

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.

Solution 3 - Php

It's not working because your $timeStamp variable is empty. Try echoing the value of $timeStamp right before creating the DateTime and you'll see. If you run this:

new DateTime('@2345234');

You don't get an error. However, if you run:

new DateTime('@');

It produces the exact error you said it gives you. You'll need to do some debugging and find out why $timeStamp is empty.

Solution 4 - Php

The following works:

$dateString = date('Ymd', $timeStamp);
$date = new DateTime($dateString);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYarinView Question on Stackoverflow
Solution 1 - PhpDawid OhiaView Answer on Stackoverflow
Solution 2 - PhpBarry SimpsonView Answer on Stackoverflow
Solution 3 - PhpJonahView Answer on Stackoverflow
Solution 4 - PhpYarinView Answer on Stackoverflow