简体   繁体   English

在PHP中将UTC转换为CST

[英]Converting UTC to CST in php

I want to convert a UTC time to CST using PHP. 我想使用PHP将UTC时间转换为CST。 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 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. 但是当我尝试使用在线转换器2018-05-29 11:44:00转换为UTC时,我得到的结果是05/29/2018 6:44 AM ,比函数返回的结果多1小时。

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. 我无法解释,但似乎只在EST / CST中发生,即使将其更改为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. 我建议改用America/Chicago这样的地方。

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 CST是UTC-06,php效果很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM