在 PHP < 5.3 中从时间戳创建日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4329872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:41:51  来源:igfitidea点击:

Creating DateTime from timestamp in PHP < 5.3

phpdatetimetimestampphp-5.2

提问by Yarin

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

在小于 5.3 的版本中,如何从时间戳创建 DateTime?

In 5.3 it would be:

在 5.3 中,它将是:

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

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

DateTime 构造函数需要一个字符串,但这对我不起作用

$date = new DateTime("@$timeStamp");

回答by Dawid Ohia

PHP 5 >= 5.3.0

PHP 5 >= 5.3.0

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

Edit:Added correct PHP version for setTimestamp

编辑:添加了正确的 PHP 版本setTimestamp

回答by Barry Simpson

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.

不过,必须这样做似乎很愚蠢。

回答by Jonah

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:

它不起作用,因为您的 $timeStamp 变量为空。在创建 DateTime 之前尝试回显 $timeStamp 的值,您会看到。如果你运行这个:

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.

它会产生您所说的确切错误。您需要进行一些调试并找出 $timeStamp 为空的原因。

回答by Yarin

The following works:

以下工作:

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