For a project I’m working on, I needed to calculate local sunrise and sunset times for a user, based on a timestamp. Because this was a “web application”, it was a mix between server-side and client-side programming. As such, I had the client providing its local time to the server, which would then choose a suitable background image based on the user’s location.
Initially, I used the hour at face value — but once I started calculating sunrise and sunset times (using the php date_sunrise and date_sunset functions), I needed to specify a GMT offset. I initially implemented it this way:
$gmt_offset = $hour - intval(date('H'));
However, I found that, while this worked for some situations, it came up with wrong answers if one of the times had rolled over into a different day. After some experimentation, I found that, for GMT+ time zones, adding 24 to the value (only if the sum would not exceed 24) returned the correct offset. Likeise, for GMT- time zones, subtracting 24 from the value (only if the difference would not be less than -23) would produce the correct offset.
// works for all GMT+ times
if($offset + 24 < 24) {
$offset += 24;
}
// works for all GMT- times
if($offset - 24 > -24) {
$offset -= 24;
}
Eventually, I realized that the program could tell whether we were looking for a GMT+ or GMT- time zone by examining the date and checking whether it was before or after the specified timestamp. (In effect, checking if the day differential was due to GMT being the next day or previous day.) As such, we finally get this code, which works for all times and time zones:
$gmt_offset = intval(date('H', $timestamp)) - intval(date('H'));
//correct for anomalies that appear when it's the next or previous day in GMT
if(time() < $timestamp) { // then we're in GMT+
if($gmt_offset + 24 < 24) {
$gmt_offset += 24;
}
} else if(time() > $timestamp) { //then we're in GMT-
if($gmt_offset - 24 > -24) {
$gmt_offset -= 24;
}
}
0 Responses to “Calculating GMT Offset from Local Time (PHP)”