【问题标题】:How do you handle timezone difference calculation in PHP?您如何处理 PHP 中的时区差异计算?
【发布时间】:2015-04-23 15:01:05
【问题描述】:

有人告诉我,以下计算用户当地时间的方法有时不起作用。在 PHP 中执行此操作的最佳方法是什么?你是做什么的?

public function getTimeOffset ($time) {
    $this->_cacheTimeOffset();  
    if ($this->timeOffsetExecuted) {
        $d = date("O");
        $neg = 1;

        if (substr($d, 0, 1) == "-") {
            $neg = -1;
            $d = substr($d, 1);
        }

        $h = substr($d, 0, 2)*3600;
        $m = substr($d, 2)*60;

        return $time + ($neg * ($h + $m) * -1) + (($this->timeOffset + $this->getDstInUse()) * 3600);
    }
    return $time;
}

【问题讨论】:

    标签: php timezone


    【解决方案1】:

    使用日期时间扩展,例如DateTime::getOffset
    DateTimeZone::getOffset

    一些国家可能已经执行了多次时区更新,
    这个方法DateTimeZone::getTransitions揭示了转换历史

    【讨论】:

    • 我目前允许用户在他们的个人资料中指定他们的时区。你是说我应该能够通过 PHP 动态拉取它,而不必询问他们的时区?
    • @Webnet - 您仍然需要用户将他们当前的时区放入他们的个人资料中。或许,您可以提供一个时区列表,让用户选择。 DateTimeZone::listIdentifiers 能够提供支持的时区的完整列表,详细信息 - php.net/manual/en/datetimezone.listidentifiers.php
    【解决方案2】:

    刚刚回答了一个非常相似的问题over here。我建议您检查一下;我非常详尽地解释了进行时区偏移计算的两种首选方法(使用简单的数学,然后是 datetimezonedatetime 类)。

    第一种方法是最简单的 (也是最合乎逻辑的)方式,那就是 存储他们的偏移量(如果你已经 拥有它,即)并将其乘以 3600(以秒为单位的 1 小时),然后添加 that 值到当前的 unix 时间戳以获取它们的最终时间 正在运行。

    另一种方法是使用 DateTimeDateTimeZone 类。 这两个类是如何工作的,如图所示 here,是你创建了两个 DateTimeZone 对象,与你的一个 时区和他们的时区;创造 两个 DateTime 对象与第一个 参数为"now" 和 第二个是参考 DateTimeZone 上面的对象 (分别);然后调用 你的时区getOffset方法 传递他们的时区对象的对象 作为第一个参数,最终 在几秒钟内为您提供偏移量 可以添加到当前的unix 时间戳来获取他们的的时间 作业需要运行。

    【讨论】:

      【解决方案3】:
      date('Z');
      

      以秒为单位返回 UTC 偏移量。

      【讨论】:

        【解决方案4】:

        快速解决方案:

        <?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>
        

        【讨论】:

        • 这只是设置时间格式,与时区无关。
        猜你喜欢
        • 2020-04-13
        • 2020-06-06
        • 1970-01-01
        • 2014-03-22
        • 2014-09-17
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        相关资源
        最近更新 更多