Timezone changes on the league website
#184 Henry, Monday, 30 June 2014 9:37 PM (Category: Web Development)
(Tags: php programming)

On the league website, we added two CSS themes for summer - a turquoise swimming pool one for daytime, and a darker night-time one. They switch at 7am and 7pm, my time. But as the players are spread all round the world, it didn't seem appropriate to change the day/night themes only at US/Eastern time. I wanted to give users the option to set their personal timezone, and have this used when displaying the theme and later on, for other things.

This is all done in PHP, and it's legacy style code.

So first of all, the code to set the theme based on the time is done like this:

$hour = (int) date ("G");
if ($hour < 7 || $hour > 19)
  $theme = "summer_night";
else
  $theme = "summer_pool";
print "
";

Then I allowed users to change their profile and set their timezone. I got some code from Stackoverflow to populate a select with all valid timezones.

Users get to set their timezones with values like "America/New_York" and "Asia/Singapore" and "Australia/Perth". Once users could set their timezones, when they login or change their timezones, I store their timezone value in their session data. I do not want to be looking this up in the database every page access they make. So once that was done, the original function to set the theme became this:

if (isset ($_SESSION['tz']))
{
  date_default_timezone_set ($_SESSION['tz']); # Set to their timezone
  $hour = (int) date ("G");
  date_default_timezone_set ("America/New_York"); # Set back to me
}
else
{
  $hour = (int) date ("G");
}

if ($hour < 7 || $hour > 19)
  $theme = "summer_night";
else
  $theme = "summer_pool";
print "
";

If the user has not set his timezone, then I continue to assume that it's done in MY timezone. But if the user has set his timezone, it will be in the session data, and I can use it. My webserver has the time set to UTC. I think this is why it was so easy to do. I've been setting system time on all my Linux systems to UTC for 20 years, and finally I get the benefit of it. So all I have to do is get the current time but filtered through the user's timezone, and extract the hour. It works. I set the timezone back to mine afterwards, as I need it in my timezone for other things. Eventually, those other things will be translated to to the user's own timezone too. This is a start.

0 comments