Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

datetime

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.

like image 433
Alex Avatar asked Jul 02 '13 13:07

Alex


1 Answers

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); 
like image 76
saamorim Avatar answered Sep 18 '22 02:09

saamorim