Java Reference
In-Depth Information
Chapter 12. New Date and Time API
This chapter covers
Why we needed a new date and time library in Java 8
Representing date and time for both humans and machines
Defining an amount of time
Manipulating, formatting, and parsing dates
Dealing with different time zones and calendars
The Java API includes many useful components to help you build complex applications.
Unfortunately, the Java API isn't always perfect. We believe the majority of experienced Java
developers will agree that date and time support before Java 8 was far from ideal. Don't worry,
though; Java 8 introduces a brand new Date and Time API to tackle this issue.
In Java 1.0 the only support for date and time was the java.util.Date class. Despite its name, this
class doesn't represent a date but a point in time with milliseconds precision. Even worse, the
usability of this class is harmed by some nebulous design decisions like the choice of its offsets:
the years start from 1900, whereas the months start at index 0. This means that if you want to
represent the release date of Java 8, which is March 18, 2014, you have to create an instance of
Date as follows:
Date date = new Date(114, 2, 18);
Printing this date produces
Tue Mar 18 00:00:00 CET 2014
Not very intuitive, is it? Moreover even the String returned by the toString method of the Date
class could be quite misleading. It also includes the JVM's default time zone, CET, which is
Central Europe Time in our case. But this doesn't mean the Date class itself is in any way aware
of the time zone!
The problems and limitations of the Date class were immediately clear when Java 1.0 came out,
but it was also clear that it wasn't fixable without breaking its backward compatibility. As a
consequence, in Java 1.1 many of the Date class's methods were deprecated, and it was replaced
with the alternative java.util.Calendar class. Unfortunately, Calendar has similar problems and
design flaws that lead to error-prone code. For instance, months also start at index 0 (at least
 
Search WWH ::




Custom Search