给定一个变量unix时间戳和一个固定的时区偏移(以秒为单位),你怎么知道当地时间是否超过了早上8点。
例如,请使用以下变量:
$timestamp = time();
$timezone_offset = -21600; //i think that's -8hrs for pacific time
答案 0 :(得分:1)
if(date("H", $timestamp + $timezone_offset) >= 8){
// do something
}
假设你认为即使是8:00:00之后的一毫秒是“早上8点”。
答案 1 :(得分:0)
使用date_default_timezone_set()在PHP中设置时区,然后使用PHP的日期时间函数(如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时间转换为格式化日期之前,您永远不必担心时区。