timezones, joda, and mysql

Ever since I created a job that was responsible for billing, I realized how important timezones and daylight savings are to application development. I had scheduled the job to run at 1:30 AM. Once a year it didn’t run (when daylight savings skipped 1:30 and jumped to 2:30), and once a year it ran twice (when daylight savings jumped back at 2 AM to 1 AM). Then I had to worry about global deployments and learned even more. Now my rule is, do everything in UTC. Convert things for users to display in their timezone, but store it all UTC.

Some notes for Java 8:

import java.time.ZonedDateTime;
converting:
ZonedDateTime zdt = ZonedDateTime.parse(input, fmt);
Timestamp sqlTs = Timestamp.from(zdt.toInstant());

ZonedDateTime zonedDateTime = ZonedDateTime.now();

ZoneId zoneId = ZoneId.of(“UTC+1”);

ZonedDateTime zonedDateTime2 =
ZonedDateTime.of(2015, 11, 30, 23, 45, 59, 1234, zoneId);
ZonedDateTime newZoneDateTime =
previousDateTime.plus(Period.ofDays(3));
ZoneId zoneId = ZoneId.of(“UTC+1”);
ZoneId zoneId2 = ZoneId.of(“Europe/Copenhagen”);

Some notes for mysql and joda
mysql has a field time datetime which is actually the number of seconds since 1970
it includes milliseconds as a fractional part.
joda has a datetime which is similar
for sprocs, pass datetime as timestamp

to convert from joda datetime to mysql’s timestamp
java.sql.Timestamp d = new java.sql.Timestamp(jodaDateTime.getMillis());

and back again
os.setDt(new DateTime(java.sql.Timestamp.valueOf(rs.getTimestamp(“dt”).toString())));

that worked but I’m hoping for a better way

Leave a Reply

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