Java 8 Date and Time

The Date-Time package, java.time, introduced in the Java SE 8 release, provides a comprehensive model for date and time.

Why do we need for a new Date and Time library ?

Non thread-safe

The existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users — not something the average developer would expect to deal with when writing date-handling code.  The new API avoids this issue by ensuring that all its core classes are immutable and represent well-defined values.

Poor design

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0 — not very intuitive. For example, java.util.Date represents an instant on the timeline — a wrapper around the number of milli-seconds since the UNIX epoch — but if you call toString(), the result suggests that it has a time zone, causing confusion among developers. The new API models its domain very precisely with classes that represent different use cases for Date and Time closely.

Use of third party date and time library

These issues, and several others, have led to the popularity of third-party date and time libraries, such as Joda-Time. The new API allows people to work with different calendaring systems in order to support the needs of users in some areas of the world, such as Japan or Thailand, that don’t necessarily follow ISO-8601.

Continue reading “Java 8 Date and Time”