New Date and Time API Looks Set for Java 8

Following refactoring work carried out over the summer to simplify and refine the API, JSR 310, the long running Java Specification Request led by Stephen Colebourne to replace Java’s complex date APIs, has been added to the feature list for Java 8. It is expected to arrive in January 2013’s milestone 6 release.

Date handling is a complex problem, and in Java has a lengthy and less than glorious history. Initial support was via java.util.Date, a rather confusingly named numeric timestamp containing both a date and a time, which is not amenable to internationalisation. It has some other frustrating aspects too, such as using inconsistent offsets for properties, so that, for example, month and hours are zero based, day-of-the-month is one based, and year has an offset of 1900.

In 1997 Java 1.1 shipped, which added support for SQL via JDBC. This also had something called a date which inherited from java.util.Date, but had a different meaning. To add to the fun, in 1998 IBM contributed a replacement API, java.util.Calendar, which is amenable to internationalisation and offers considerable flexibility, but at the cost of a great deal of complexity even for relatively simple problems. Worse, all the properties in both java.util.Date and java.util.Calendar are mutable, so that, for example, any property of type Date (or of type Time or Timestamp) needs to be cloned when being returned from an accessor.

It wasn’t until 2005 that Stephen Colebourne’s popular and widely-used Joda-Time library was released, improving the situation considerably, but requiring the use of an external library. JSR 310 builds on that experience, offering a replacement for both java.util.Date and java.util.Calendar in the Java SE standard library itself.

310 is a large API, but having used it a little I feel that it is consistent and easy to comprehend. In the latest version it deals with the complexity problem by offering a high level API primarily for use by applications, and a low level API for frameworks and other cases that may not be directly supported, so for example a developer could use the low level API to extend the supported set of date-time fields (YEAR, MONTH, DAY_OF_MONTH, HOUR and so on), to add a new field, such as “hour-of-fortnight”.

The high level API provides a set of classes such as ZonedDateTime (for storing a date and time with a time-zone), LocalDate, LocalTime, and LocalDateTime for working with “human” dates and times, and Instant for a numeric timestamp useful for things like logging, analogous to Java.util.Date. All these classes are immutable and thread-safe.

With JSR 310 now set for inclusion in Java 8, the ThreeTen project has been established via OpenJDK to do the integration work. The project which provides the reference implementation for 310 is hosted on SourceForge with source code available on GitHub.

Java 8 itself is due for release in October 2013.