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

后端 未结 5 1930

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

Exception: DateTime::_construct(): Failed to parse

相关标签:
5条回答
  • 2020-12-24 11:11

    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 '';
        }
    
    0 讨论(0)
  • 2020-12-24 11:17

    Use the createFromFormat method:

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

    UPDATE

    I now recommend the use of Carbon

    0 讨论(0)
  • 2020-12-24 11:19
    $start_date = new DateTime();
    $start_date->setTimestamp($dbResult->db_timestamp);
    
    0 讨论(0)
  • 2020-12-24 11:22

    change your code to this

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

    and it will work fine

    0 讨论(0)
  • 2020-12-24 11:24

    You should use setTimestamp instead, if you hardcode it:

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

    in your case

    $start_date = new DateTime();
    $start_date->setTimestamp($dbResult->db_timestamp);
    
    0 讨论(0)
提交回复
热议问题