Ical and Daylight Savings time in PHP

The film festival I volunteer for is usually in February, but this year it takes place during the same weekend as the switch to Daylight Savings time.

For a 7-hour window before Daylight Savings Time, my iCal events were off by an hour

For a 7-hour window before Daylight Savings Time, my iCal events were off by an hour

Years ago I built a link on each detail page that lets you add the movie to your calendar via ical.

I actually did pretty well. I remember time zones being a huge pain, but whatever solution I ended up with worked for years. Even this year, most of the events are correct. I don’t know whether I wrote this function or found it, but it is the magic bullet.

private function unixToIcal($uStamp = 0, $tzone = NULL) 
{
    if ($tzone === NULL)
    {
        $tzone = date("Z", $uStamp);
    }
    $uStampUTC = $uStamp - ($tzone);
    $stamp  = date("Ymd\THis\Z", $uStampUTC);
    return $stamp;       
}

Unfortunately, starting with the 7:15 show on Saturday, the times are off by 1 hour. The 7:15 p.m. show gets added to your calendar at 8:15 p.m. And the 9:30 p.m. show is added at 10:30 p.m.

Astute readers will notice that the $uStampUTC variable is calculated by adding a difference between the (local) event time and UTC.  The problem is that at the time of the event — $uStamp — Daylight Savings has not happened yet. But at UTC time of the event — at $uStampUTC — Daylight Savings has begun.

After some thought and some debugging, I found a way to do this without adding and subtracting 7, but rather letting the computer do all of the adjusting.

Check the new improved method here:

private function unixToIcal($uStamp = 0) 
{
    $revert = date_default_timezone_get();
    date_default_timezone_set('UTC');
    $stamp  = date("Ymd\THis\Z", $uStamp);
    date_default_timezone_set($revert);
    return $stamp;       
}

I love it when a fix is shorter and simpler than the problem. In this case, we take the event time — $uStamp. Rather than converting time zones ourselves, we let PHP convert to UTC for us at the same time as it formats the date in ical format with:

date_default_timezone_set('UTC')

Then just to be polite we revert back to the system’s time zone.

Advertisements
This entry was posted in Debugging, PHP, Web programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s