I want to convert a UTC time to CST using PHP. After googling I got a function
function date_convert($dt, $tz1, $df1, $tz2, $df2) {
// create DateTime object
$d = DateTime::createFromFormat($df1, $dt, new DateTimeZone($tz1));
// convert timezone
$d->setTimeZone(new DateTimeZone($tz2));
// convert dateformat
return $d->format($df2);
}
echo date_convert('2018-05-29 11:44:00', 'UTC', 'Y-m-d H:i:s', 'CST', 'Y-m-d H:i:s');
The output is
2018-05-29 05:44:00
But when I tried converting 2018-05-29 11:44:00 to UTC using online converter, I got the result as 05/29/2018 6:44 AM, which is 1 hour more than what the function returns.
Can anyone help me to find the correct output? Thanks in advance.
I can't explain it, but it only seems to happen with EST/CST, even with changing it to a D.
$n = new DateTime(); // 'date' => '2018-05-29 09:45:01.000000' America/New_York
$n->setTimeZone(new DateTimeZone('UTC')); // 'date' => '2018-05-29 13:45:01.000000'
$n->setTimeZone(new DateTimeZone('EDT')); // 'date' => '2018-05-29 08:45:01.000000'
But if you use a place instead of a timezone, it works well:
$n->setTimeZone(new DateTimeZone('America/New_York')); // 'date' => '2018-05-29 09:45:37.000000'
$n->setTimeZone(new DateTimeZone('America/Chicago')); // 'date' => '2018-05-29 08:45:37.000000'
I'd suggest using a place such as America/Chicago
instead.
Try this;
function date_convert($time, $oldTZ, $newTZ, $format) {
// create old time
$d = new \DateTime($time, new \DateTimeZone($oldTZ));
// convert to new tz
$d->setTimezone(new \DateTimeZone($newTZ));
// output with new format
return $d->format($format);
}
echo date_convert('2018-05-29 11:44:00', 'UTC', 'CST', 'Y-m-d H:i:s');
Output:
2018-05-29 05:44:00
CST is UTC-06, php works well