Perils of Java Date Formats

Java has a rather sordid history with dates. In the beginning, Date was suppose to be the way to manage dates, which sounded rather logical. You could construct a Date from various component values (month, day, year and time), and internally it was measured as the number of milliseconds from epoch.
Once JDK 1.1 came out, the advent of Calendar brought some new capabilities and deprecated many of the rudimentary functions present in Date. From a Calendar, it was possible to add and subtract specific components in a date; for example, you could add 90 days and determine what the new Date will be. With JDK 1.8 the introduction of a revamped date and time API brings this in line with JSR 310 and further enhances the handling of dates and times.

Formatting dates is the process of converting strings to dates and vice versa. For example, if a user inputs “01/01/2015” you may use something like SimpleDateFormat to convert this to a real Date:

There are a number of benefits here, LocalDate is a date-only entity without a time component. This makes it possible to represent dates without respect to time. Additionally, formatting an invalid date:

This is not totally entirely correct in the context of daylight savings time, for EDT (America/New York) the 2AM hour was skipped on 3/8/15. Fortunately, the Java date time API offers a ZonedDateTime which can take this into consideration:

There are plenty of other reasons to start leveraging the new Java date time API, in addition to feature parity with the existing Java Date and DateFormat API’s, the new date time API provides methods to adjust dates just like the Calendar has been able to do. For example:

LocalDate ld = LocalDate.now().plusDays(2);

This creates a LocalDate for today and adds 2 days to it using a builder pattern. By comparison, the Calendar operation would appear like so:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 2);

Same operation of adding two days to the current date; however, it takes two lines of code and requires you to select a field from the somewhat cryptic set of possible fields on the Calendar. For example, do you think you can add Calendar.FEBRUARY to the calendar? Probably not, but it certainly won’t complain when you do it.

If you are still supporting a JDK earlier than 1.8, the Joda library is functionally equivalent and would be a great way to get started.

As a developer, one of the tools that makes me more productive is a good text editor. While IDE environments are replete with a wide assortment of powerful editing tools, they often miss the mark on Read more…

After managing a number of Java projects with Maven, the 2.1 release of the Twig Cassandra JDBC driver fork has prompted me to revisit the build process. This was a significant rewrite of the existing Apache Read more…