【问题标题】:How can I create a DateTime object from a string that is already in a specific timezone?如何从已经在特定时区的字符串创建 DateTime 对象?
【发布时间】:2014-01-15 10:03:12
【问题描述】:

我在所有默认时区设置都设置为 UTC 的环境 (wordpress) 中工作。

在其中,我想创建一个计时器函数,该函数始终以本地服务器时间 (+8) 处理时间。

我们的目标是有一个函数可以将 DateTime 对象返回到任何给定的日期(以'Y-m-d H:i:s' 格式输入,始终使用本地 +8 时区

function datetime_obj($date = NULL) {
    $date_new = new DateTime($date);
    $date_new->setTimezone(new DateTimeZone('Asia/Hong_Kong'));
    return $date_new;
}

当我尝试获取今天的日期/时间信息 ($date = NULL) 时,这非常有用。但是,如果我将现有时间(HKG 时间)作为字符串(例如来自 MySQL 数据库中的日期时间字段),我无法从中生成新的日期时间对象,因为它被视为 UTC。上述函数生成的 DateTime 对象总是增加 8 小时。

如何更改上述函数,以便插入的 $date 被接受为已经在正确的 +8 时区,而不是更改 +8 作为输出?

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    我没试过,但是文档说:

    public DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
    

    时间:日期/时间字符串。有效格式在日期和时间中解释 格式。此处输入 NULL 获取当前时间 $timezone 参数。

    timezone:一个 DateTimeZone 对象,表示 $time 的时区。如果 $timezone 省略,将使用当前时区。

    注意:$timezone 参数和当前时区被忽略 当 $time 参数是 UNIX 时间戳时(例如 @946684800) 或指定时区(例如 2010-01-28T15:00:00+02:00)。

    http://at2.php.net/manual/en/datetime.construct.php

    所以...这个:

    $date_new = new DateTime($date."+08:00");
    

    或者这个:

    $date = new DateTime($date, new DateTimeZone('Asia/Hong_Kong'));
    

    应该做的工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多