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