Creating DateTime from timestamp in PHP < 5.3

北城余情 提交于 2019-11-30 04:37:07
Dawid Ohia

PHP 5 >= 5.3.0

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

Edit: Added correct PHP version for setTimestamp

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.

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.

The following works:

$dateString = date('Ymd', $timeStamp);
$date = new DateTime($dateString);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!