G4k'
G4k'

Reputation: 23

How to convert this date with php

How to convert this date format that is coming from javascript:

Thu Mar 04 2021 18:00:00 GMT-0300 (Brasilia Standard Time)

These formats are not working

$date = date('c', strtotime(Thu Mar 04 2021 18:00:00 GMT-0300 (Brasilia Standard Time));

$date = date('Y-m-d h:i:s', strtotime(Thu Mar 04 2021 18:00:00 GMT-0300 (Brasilia Standard Time));

The date goes back to 1969

Any insights?

Upvotes: 1

Views: 106

Answers (2)

Sammitch
Sammitch

Reputation: 32232

I would suggest using the modern DateTime interface and specifying a proper format, rather than having PHP try to guess how to interpret the date string. You can also use the + specifier to ignore trailing data rather than having to edit your input in advance.

$string = 'Thu Mar 04 2021 18:00:00 GMT-0300 (Brasilia Standard Time)';
$date = DateTime::createFromFormat('D M d Y H:i:s T+', $string);

var_dump($date, $date->format('c'));

Output:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2021-03-04 18:00:00.000000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "-03:00"
}
string(25) "2021-03-04T18:00:00-03:00"

Upvotes: 0

Maximiliano Bertiaux
Maximiliano Bertiaux

Reputation: 80

may you should try skip "(Brasilia Standard Time)" in the data submit.

$date = date('Y-m-d h:i:s', strtotime("Thu Mar 04 2021 18:00:00 GMT-0300"));
var_dump($date);

I got this result:

string(19) "2021-03-04 01:00:00"

Edit: If you can 'skip' that string, you can do something like:

 $strTime = "Thu Mar 04 2021 18:00:00 GMT-0300 (Brasilia Standard Time)";
 $strTime = str_replace($strTime, ""," (Brasilia Standard Time)");
 $date = date('Y-m-d h:i:s', strtotime($strTime));

 var_dump($date);

output:

string(19) "1969-12-31 04:00:00"

Upvotes: 1

Related Questions