Reputation: 422
I have date in the following format -
"Thu Jul 29 2021 17:47:12 GMT+0530 (India Standard Time)"
I want convert this date using php in the following format -
"2021-07-29T17:47:12"
I tried following ways so far but id didn't work -
//one way
$st = "Thu Jul 29 2021 17:47:12 GMT+0530 (India Standard Time)";
$st = strtotime($st);
$date = new DateTime($st, new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone('IST'));
//other way
$st = "Thu Jul 29 2021 17:47:12 GMT+0530 (India Standard Time)";
$st = strtotime($st);
$format = "Y-m-d";
$newdate = date_format(date_create($st), $format);
print_r($newdate);
There are many questions already available for date conversion on stack overflow itself but none of them answer my question as my date to convert is in different format so, please help me if anyone can. Thanks in advance.
Upvotes: 0
Views: 83
Reputation: 141
Another possible solution:
$date = 'Thu Jul 29 2021 17:47:12 GMT+0530 (India Standard Time)';
var_dump(DateTime::createFromFormat('D M d Y H:i:s+', $date)->format('Y-m-d\TH:i:s') );
Output
string(19) "2021-07-29T17:47:12"
+
If this format specifier is present, trailing data in the string will not cause an error, but a warning instead
Upvotes: 1
Reputation: 48049
You may have over-thought it.
Since you are ignoring any timezone differences, just truncate the characters at the end of string that are unnecessary then have strtotime()
parse what is left.
Code: (Demo)
$date = 'Thu Jul 29 2021 17:47:12 GMT+0530 (India Standard Time)';
echo date('Y-m-d\TH:i:s', strtotime(substr($date, 0, 24)));
Output:
2021-07-29Z17:47:12
Upvotes: 1