Skip to content
Advertisement

PHP: Get timestamp from date format YYYY-MM-DD HH:MM:SS GMT+HH:MM

I’m reading lines from a *.txt file and get strings (date formats) in this style:

2017-10-19 20:51:54 GMT+08:00
2020-03-31 13:19:31 GMT-08:00
2018-04-10 14:35:17 GMT

With the function DateTime::createFromFormat, I want to convert such lines into a time string. After that, I would like to get the timestamp with getTimestamp();. So, currently my code looks like this ($date is my read line):

$date = DateTime::createFromFormat("Y-m-d H:i:s", $date);
$timeStamp = $date->getTimestamp();

When I try to do this, I get this error message:

Fatal error: Uncaught Error: Call to a member function getTimestamp() on bool in ...

Does anyone have an idea how to solve this problem?


Edit:
Regarding Gordon’s comment, I also tried to add the missing parts (“GMT” => e and “+08:00” => P) as well, like this:
$date= DateTime::createFromFormat("Y-m-d H:i:s eP", $date);

Advertisement

Answer

You are getting this error because the date provided does not match the format specified.

Add the following line after createFromFormat() call –

var_dump(DateTime::getLastErrors());

The above line will return the error. The error message is – “Trailing data“. This is because of “GMT+08:00” in the string.

For processing it properly you should provide the optional third parameter to createFormFormat which is timezone and it expects it to be a DateTimeZone object. So update your createFromFormat function as –

$timezone = new DateTimeZone('GMT+08:00');
$date = "2017-10-19 20:51:54";
$date = DateTime::createFromFormat("Y-m-d H:i:s", $date, $timezone);

I hope this helps. You will have to separate the date from the timezone and process it as mentioned above.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement