Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

June 03 2011

Handling Daylight Savings Time in Java

After the recent Daylight Savings Time switch here in the US, we noticed our timestamps on lead alerts were off in some markets by an hour.  We had been using Greenwich Mean Time (GMT) to set user’s time zone to make sure alerts were relevant for each market, and learned that this is not sufficient to handle the DST switches.  Fortunately, the Java TimeZone library supports time zones in a variety of formats and we learned by using the “America/Denver” format instead of “GMT-7″ it accounts for Daylight Savings Time.

To test our theory and take advantage of a chance to “geek out”, something my CEO duties prevent more and more as our company grows, I built a simple Java Server Page (JSP) illustrating the alternate way of storing time zones.  See below for a useful code snippet.

<%@ page import=”java.text.*, java.util.*, java.sql.*” %>

<%
String userTzPref = “America/Denver”;
String inquiryTimestamp = “2011-06-02 19:21:53″;

// assemble message
SimpleDateFormat sdf = new SimpleDateFormat(“MM/dd/yyyy hh:mm a”);
sdf.setTimeZone(TimeZone.getTimeZone(userTzPref));
String time = sdf.format(Timestamp.valueOf(inquiryTimestamp));
%>

<html><head><title>Timestamp Test</title></head>
<body>
<h1><%= time %></h1>
<h2><%= userTzPref %>  (time zone)</h2>
<h2><%= inquiryTimestamp %>  (inquiry timestamp in DB)</h2>
<body>
</html>

You can test the time zone changes by editing the userTzPref to “America/Los_Angeles” or “America/Chicago” or “America/New_York” or even “America/Phoenix” and confirm your timestamps display the proper time for the user’s locale.  I hope this is useful in case you too face issues with timestamps and Daylight Savings Time.  Happy coding!

Don't be the product, buy the product!

Schweinderl