Converting timezone offsets to string to find the current time there in PHP
It's pretty easy to find out what the current hour is in PHP right? If I want to know if it's between 12am to 1am I would use:
if(date('H') == '00')
{
echo "It's after midnight! But not quite 1am";
}
Real simple. But what if I want to find out if it's 12:xx am in a different timezone? Well first we need to know the timezone we want. In order to use PHP5's DateTimeZone(), we need to know the timezone string associated with the timezone you want. For example, Central Standard Time(CST) is under the string "America/Chicago". This isn't a very nice string to store thousands of times in a database and really isn't too descriptive if you haven't heard of the city or region that the string uses. A better way to store is the offset from GMT, which CST is -6.0 hours. Luckily enough there is a php function that converts this offset to the needed string.
//The functions expects seconds and not hours.
$seconds = -6.0*60*60;
$tz = timezone_name_from_abbr("", $seconds, 0);
$dateTZ = new DateTimeZone($tz);
Now that we have a DateTimeZone object with the timezone we are looking for. How do I find out if its 12:xx there?
//The functions expects seconds and not hours.
$seconds = -6.0*60*60;
$tz = timezone_name_from_abbr("", $seconds, 0);
$dateTZ = new DateTimeZone($tz);
//this gets the current offset from GMT.
$offset = $dateTZ->getOffset(new DateTime(date('Y-m-d')))/60/60;
//We use gmdate() here to get the current hour in GMT
if(gmdate('H')+ $offset == '00')
{
echo "It's after midnight! But not quite 1am";
}
This may look more complex than it needs to be. Why not just check if gmdate('H') + our stored offset ('-6.0') == 00? Well, the above way is used to take into account Daylight Savings Time. In the summer months, we are actual -5 hours from GMT. Because of these fluctuations, it's better just to leverage PHP. Sure it makes us write a couple extra lines of code but think of all those long summer days it gives you too.