Dealing with Times and Time Zones

My apologies if I am a bit behind the game on this but I am a bit stuck on how to deal with the storage of time zone and time data (including daylight savings time). Here is my example.

I have to save a whole bunch of times in a database. I want to store all of these times in one time zone (UTC) to maintain data quality. When I display the time to the user, I want to format it into the local time zone of the user.

Lets say I want to store 9:30 AM eastern time into the database. In UTC this would be 14:30 UTC (because EST is UTC-5). So now I recall the time 14:30 from the database and place it into a data object with the time zone of UTC and format the date over to the America/New_York. When I do this the time will print 10:30 AM EDT because daylight savings time is in effect. This makes the value I stored in the database incorrect.

What I want to know is the best way to properly store and recall time and time zone information so it is consistent regardless of daylight savings. Is there a better way of storing and handling these times? Are there any accepted practices in dealing with these problems?

Thanks for your help.

Here’s how I understand your problem: you store 9:30 EST (GMT-5) in New York on November 1, 2009 in GMT, and retrieve 14:30 GMT on June 1, 2009, which is EDT, which comes out to 10:30 (GMT-4).

If you store the result of Calendar.getTimeMillis() instead of a local time converted to GMT, you’ll have a consistent base time (number of milliseconds since January 1, 1970, 00:00:00 GMT) to work with.

When you retrieve the long, you can reconstitute the Calendar, set the time zone, and use .get( Calendar.HOUR_OF_DAY ), etc, to output the correct time.

rushiku is correct. (As always… :slight_smile: )

The key with storing anything that has variable formats like dates is to store the value in its lowest common denominator. Which in this case is milliseconds.

You can then format the time as needed. On a side note, most databases will store time in milliseconds but format the output for the timezone of the server.

BTW, here are some interesting design patters that deal with time:
http://martinfowler.com/ap2/timeNarrative.html

Quite a fascinating read.

Storing it as a long makes sense. That way I can recreate the Date objects quite easily. Thank you both for your help.

Store your date in your database as a date for your database. Most databases store dates as integers behind the scenes.

The database will then generally present dates to you from queries as the local timezone of your sever.

If you need to display different timezones to users, then it is best to figure out that users timezone at registration time and then use that timezone to display dates to the user.

The only thing you really need to worry about is that your JVM and your database server are set to the same timezone.

Hope that clarification works.