【问题标题】:PHP - Local vs UTC Time Comparison with Timezone OffsetPHP - 本地与 UTC 时间与时区偏移的比较
【发布时间】:2012-12-07 01:09:34
【问题描述】:

给定一个可变的 unix 时间戳和一个固定的时区偏移量(以秒为单位),您如何判断当地时间是否超过上午 8 点。

例如,取以下变量:

$timestamp = time();
$timezone_offset = -21600;  //i think that's -8hrs for pacific time

【问题讨论】:

    标签: php date utc


    【解决方案1】:
    if(date("H", $timestamp + $timezone_offset) >= 8){
        // do something
    }
    

    假设您认为即使超过 8:00:00 的一毫秒也是“早上 8 点”。

    【讨论】:

    • 谢谢,就这样。所以如果我想添加一个 15 分钟的缓冲区,那么我会使用“H”获取日期的输出,使用“i”获取分钟的输出并分别比较?
    【解决方案2】:

    您在 PHP 中使用 date_default_timezone_set() 设置您的时区,然后使用 PHP 的 datetime 函数(如 date 或 DateTime 对象)根据设置的时区检查时间。 PHP 会为你做正确的事,将时间调整到指定的时区。

    $timestamp = 1354794201;
    date_default_timezone_set("UTC"); // set time zone to UTC
    if (date("H", $timestamp) >= 8) { // check to see if it's past 8am in UTC
        echo "This time stamp is past 8 AM in " . date_default_timezone_get() . "\n";
    }
    
    date_default_timezone_set("America/New_York"); // change time zone
    if (date("H", $timestamp) >= 8) { // Check to see if it's past 8am in EST
        echo "This time stamp is past 8 AM in " . date_default_timezone_get() . "\n";
    }
    

    此代码的输出

    /* This time stamp is past 8 AM in UTC */
    

    你也可以用 DateTime 做同样的事情......

    $timestamp = 1354794201;
    $date = new DateTime("@{$timestamp}"); // create the DateTime object using a Unix timestamp
    $date->setTimeZone(new DateTimeZone("UTC")); // set time zone to UTC
    if ($date->format("H") >= 8) { // check to see if it's past 8am in UTC
        echo "This time stamp is past 8 AM in {$date->getTimezone()->getName()}\n";
    }
    
    $date->setTimeZone(new DateTimeZone("America/New_York")); // change time zone
    if ($date->format("H") >= 8) { // Check to see if it's past 8am in EST
        echo "This time stamp is past 8 AM in {$date->getTimezone()->getName()}\n";
    }
    

    上述代码的输出也是……

    /* This time stamp is past 8 AM in UTC */
    

    Unix 时间与时区无关。这就是使用 Unix 时间作为传输层的意义所在。在将时间戳从 Unix 时间转换为格式化日期之前,您永远不必担心时区。

    【讨论】:

    • 感谢您花时间写这篇文章。虽然我特别希望以秒为单位使用时区偏移量。
    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多