【问题标题】:Converting UTC to CST in php在php中将UTC转换为CST
【发布时间】:2018-11-08 04:33:51
【问题描述】:

我想使用 PHP 将 UTC 时间转换为 CST。谷歌搜索后我得到了一个函数

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');

输出是

2018-05-29 05:44:00

但是当我尝试使用 online converter2018-05-29 11:44:00 转换为 UTC 时,我得到的结果是 05/29/2018 6:44 AM,比函数返回的时间多 1 小时。

谁能帮我找到正确的输出?提前致谢。

【问题讨论】:

  • 我猜目标时区当前处于夏令时模式,这使它成为 CDT,这是一个小时偏移量。 PHP 考虑了这一点。

标签: php datetime timezone utc


【解决方案1】:

我无法解释,但它似乎只发生在 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'

但如果你使用地点而不是时区,效果会很好:

$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'

我建议改用America/Chicago 之类的地方。

【讨论】:

  • 确实,总是使用完整的时区标识符 - 如第二个示例所示。
【解决方案2】:

试试这个;

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');

输出:

2018-05-29 05:44:00

CST 是 UTC-06,php 运行良好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-21
    • 2021-08-22
    • 2021-04-10
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多