【发布时间】:2012-12-07 01:09:34
【问题描述】:
给定一个可变的 unix 时间戳和一个固定的时区偏移量(以秒为单位),您如何判断当地时间是否超过上午 8 点。
例如,取以下变量:
$timestamp = time();
$timezone_offset = -21600; //i think that's -8hrs for pacific time
【问题讨论】:
给定一个可变的 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 点”。
【讨论】:
您在 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 时间转换为格式化日期之前,您永远不必担心时区。
【讨论】: