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

PhpDatetime

Php Problem Overview


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

>Exception: DateTime::__construct(): Failed to parse time string (1372622987) at position 8 (8): Unexpected character in 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:

>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.

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.

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

Use the createFromFormat method:

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

UPDATE

I now recommend the use of Carbon

Solution 3 - Php

change your code to this

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

and it will work fine

Solution 4 - Php

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 '';
    }

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PhpsaamorimView Answer on Stackoverflow
Solution 2 - PhpRob WView Answer on Stackoverflow
Solution 3 - PhpAbani MeherView Answer on Stackoverflow
Solution 4 - PhpSam DeeringView Answer on Stackoverflow
Solution 5 - PhpBastien DView Answer on Stackoverflow