Friday, March 2, 2012

Dealing with Time Zone Changes


Creative Commons Licence

This work is licenced under a Creative Commons Licence.

One of the things a BlackBerry Smartphone does very well is manage calendars. Whether through the BlackBerry Enterprise Server, a Google, Yahoo or other on-line account with calendar support the BlackBerry provides two way wireless synchronization with many appointment organization systems. One thing it doesn't to well, or at all really, is allow synchronization with public calendars. Many groups to which one might belong publish calendars either directly or through one Google, Yahoo, etc. It seems obvious that I would like to be able to pull this data into my BlackBerry periodically so I can more easily manage my time.

There is a standard protocol called vCalendar for exchanging data between applications. Unfortunately it is not the lingua franca one might hope for. One of the issues I'm faced with trying to write software to do this is that not all applications deal with the time change associated with Daylight Savings Time the same way. One source I use provides the time in Greenwich Mean Time relative to standard time and expects the consumer to deal with the differences imposed by Daylight Savings. This is how I'm currently dealing with it:

// Get the default timezone for the device, and the offset from GMT

TimeZone tz = TimeZone.getDefault();
int rawOff = tz.getRawOffset();   

/*
** Use Date objects with a Calendar object to decompose the start and 
** stop times which are milliseconds from the Unix epoch.
*/

Date dStart = new Date(start);
Date dStop = new Date(stop);
 
Calendar c = Calendar.getInstance();
c.setTime(dStart);

// Get the offset from GMT for the time of the event start
int startOff = tz.getOffset(1, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
 c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.DAY_OF_WEEK), c.get(Calendar.MILLISECOND));
   
c.setTime(dStop);

// Get the offset from GMT for the time of the event stopt
int stopOff = tz.getOffset(1, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
 c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.DAY_OF_WEEK), c.get(Calendar.MILLISECOND));
 
// Correct for a change between standara and daylight savings time  
if (startOff != rawOff) {
 start += rawOff - startOff;
 event.setDate(BlackBerryEvent.START, 0, 0, start);
}
   
if (stopOff != rawOff) {
 stop += rawOff - stopOff;
 event.setDate(BlackBerryEvent.END, 0, 0, stop);
}

No comments:

Post a Comment