PHP DateTime __construct() 无法解析位置 x 处的时间字符串 (xxxxxxxx)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17427503/
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:52:04  来源:igfitidea点击:

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

phpdatetime

提问by Alex

I had this construction error when trying to creating a new DateTime object using a timestamp:

尝试使用时间戳创建新的 DateTime 对象时出现此构造错误:

Exception: DateTime::_construct(): Failed to parse time string (1372622987) at position 8 (8): Unexpected character in DateTime->_construct()

异常:DateTime::_ construct():无法解析位置 8 (8) 处的时间字符串 (1372622987):DateTime->_construct() 中出现意外字符

The object creation code is:

对象创建代码为:

$start_date = new DateTime( "@{$dbResult->db_timestamp}" );

Where $dbResult->db_timestamp is a valid unix timestamp taken from a database. The timestamp in question was:

其中 $dbResult->db_timestamp 是取自数据库的有效 unix 时间戳。有问题的时间戳是:

1372622987

1372622987

I would understand this error for invalid formats being passed, but this is a genuine timestamp.

我会理解传递无效格式的错误,但这是一个真正的时间戳。

The reason this is very strange: I since ran a script to create a new DateTime object with the timestamp passed in as a hard coded value, and it reported no errors.

这很奇怪的原因是:我运行了一个脚本来创建一个新的 DateTime 对象,其中时间戳作为硬编码值传入,并且它没有报告任何错误。

This seems to have been a one off, but I need an explanation if there is one, as I can't afford for this to happen again.

这似乎是一次性的,但如果有的话,我需要一个解释,因为我无法承受再次发生这种情况。

回答by saamorim

You should use setTimestamp instead, if you hardcode it:

如果您对其进行硬编码,则应改用 setTimestamp:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

在你的情况下

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

回答by Half Crazed

Use the createFromFormatmethod:

使用createFromFormat方法:

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

UPDATE

更新

I now recommend the use of Carbon

我现在推荐使用

回答by Abani Meher

change your code to this

将您的代码更改为此

$start_date = new DateTime( "@" . $dbResult->db_timestamp );

and it will work fine

它会正常工作

回答by Bastien D

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

回答by Sam Deering

This worked for me.

这对我有用。

   /**
     * return date in specific format, given a timestamp.
     *
     * @param  timestamp  $datetime
     * @return string
     */
    public static function showDateString($timestamp)
    {
      if ($timestamp !== NULL) {
        $date = new DateTime();
        $date->setTimestamp(intval($timestamp));
        return $date->format("d-m-Y");
      }
      return '';
    }