Skip to content
Advertisement

Date conversion in PHP

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.

Advertisement

Answer

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-dTH:i:s', strtotime(substr($date, 0, 24)));

Output:

2021-07-29Z17:47:12
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement