2

I'm stuck trying to convert a string in a Javascript format into a format I can use in PHP for filtering.

An example of the date string that I'm given is "Thu Jan 01 2015 00:00:00 GMT-0800 (Pacific Standard Time)"

Let's say I have that assigned to a variable $z. When I run the following, I get an unexpected result:

$z = "Thu Jan 01 2015 00:00:00 GMT-0800 (Pacific Standard Time)";
$value = date('Y-m-d H:i:s', strtotime($z));

This gives me $value = "1970-01-01 00:00:00", obviously not what I wanted. I've also tried the following with no luck:

$value = DateTime::createFromFormat('D M d Y H:i:s',$z); //Fails

Now I'm pretty sure that the timezone info is what is messing everything up, but I just can't seem to figure out what to do here. I'm using Laravel 5, so I've also attempted similar operations with Carbon. Does anyone have any suggestions?

ChemProfMatt
  • 139
  • 10

1 Answers1

4

Your code gives the error Trailing data (using DateTime::getLastErrors()). This is because your pattern doesn't take in consideration the timezone after the time ( GMT-0800 (Pacific Standard Time) ) .

So you need to use the T operator to match the GMT-0800 part, and a generic + symbol to just igonre the rest. Your final pattern will be:

$value = DateTime::createFromFormat('D M d Y H:i:s T +',$z);

which gives

 DateTime Object
(
    [date] => 2015-01-01 00:00:00.000000
    [timezone_type] => 1
    [timezone] => -08:00
)

Good luck !

Wahib Mkadmi
  • 627
  • 2
  • 9
  • 26
  • 2
    Wahib: Thanks for the help on this! You know, I tried the format 'D M d Y H:i:s |' before because I thought the pipe symbol would do what the + did. Apparently not. Your help is MUCH appreciated! – ChemProfMatt Jul 13 '15 at 05:51
  • @Wahib,Thanks man! I went as far as DateTime::createFromFormat('D M d Y H:i:s e',$z); to create date from "Thu Jan 01 2015 00:00:00 GMT-0800". Replaced e with your suggested T + and it worked like a glove for the full date with (Standard Time). Much appreciated! – Striker Dec 12 '19 at 20:04