Date offsets in PHP

Date offsets in PHP

I have been alerted to a problem with some of our CTS course search results which were displaying the wrong availability times. The times for the sessions are held in UNIX timestamp form which turned out to be the root of the problem. Each of the courses are due to start at 9am but two were presented as 8am on the website. Adding to the confusion was the fact that the HTML web service output showed the correct times where the XML based information I use for the website results was showing the wrong times – from the same source data.

If storing a ‘proper’ Datetime you are specifying the time e.g. 10:15am and this time will be displayed regardless of your Daylight Saving Time status. However, a UNIX timestamp has no information beyond an Integer which has no DST context.

Roughly following the example at http://php.net/manual/en/datetime.getoffset.php I create a DateTime object using the availability timestamp of the course in question ($datestamp). Then I test for offset in seconds at the time of the datestamp.

$summer = date_create(date('D jS M Y g:i A',$datestamp), timezone_open('Europe/London'));       
$sofset =  date_offset_get($summer) ;

The offset turned out to be +3600 seconds for the two courses in April due to the DST offset shown here on the website EpochConverter:

It was then a simple case of checking for a non zero offset and adding/subtracting from the course timestamp where necessary.

I realise that using the named timezone is not the best approach so I will investigate how to correct this for other timezones at some point.

Correction



$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions($datestamp,$datestamp);
$transition = $transitions[0]['offset'];
if ($transition != 0) {
$datestamp = $datestamp + $transition;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.