問題描述
PHP ‑ Параўнанне лакальнага і UTC часу са зрушэннем гадзіннага пояса (PHP ‑ Local vs UTC Time Comparison with Timezone Offset)
Given a variable unix timestamp and a fixed timezone offset in seconds, how can you tell if local time is past 8am.
For example, take the following variables:
$timestamp = time();
$timezone_offset = ‑21600; //i think that's ‑8hrs for pacific time
‑‑‑‑‑
參考解法
方法 1:
if(date("H", $timestamp + $timezone_offset) >= 8){
// do something
}
Assuming you consider even a millisecond past 8:00:00 is "past 8am".
方法 2:
You set your timezone in PHP using date_default_timezone_set() and then use PHP's datetime functions like date or DateTime object to check the time according to the set timezone. PHP will do the right thing for you and adjust the time to the specified timezone.
$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";
}
Output from this code
/* This time stamp is past 8 AM in UTC */
You can do the same thing with DateTime as well...
$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";
}
Output from the above code is also...
/* This time stamp is past 8 AM in UTC */
Unix time is time zone agnostic. That's the point of using Unix time as a transport layer. You never have to worry about time zones until it comes time to translate your time stamp from Unix time to a formatted date.