Creating DateTime from timestamp in PHP < 5.3

2019-02-02 19:31发布

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

4条回答
手持菜刀,她持情操
2楼-- · 2019-02-02 19:50

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.

查看更多
等我变得足够好
3楼-- · 2019-02-02 19:53

PHP 5 >= 5.3.0

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

Edit: Added correct PHP version for setTimestamp

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-02 20:00

The following works:

$dateString = date('Ymd', $timeStamp);
$date = new DateTime($dateString);
查看更多
在下西门庆
5楼-- · 2019-02-02 20:13

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.

查看更多
登录 后发表回答