Java Reference
In-Depth Information
Calendar got rid of the 1900 offset for the year). Even worse, the presence of both the Date and
Calendar classes increases confusion among developers. Which one should you use? In addition,
some other features such as the DateFormat, used to format and parse dates or time in a
language-independent manner, work only with the Date class.
The DateFormat also comes with its own set of problems. For example, it isn't thread-safe. This
means that if two threads try to parse a date using the same formatter at the same time, you may
receive unpredictable results.
Finally, both Date and Calendar are mutable classes. What does it mean to mutate the 18th of
March 2014 to the 18th of April? This design choice can lead you into a maintenance nightmare,
as you'll learn in more detail in the next chapter, which is about functional programming.
The consequence is that all these flaws and inconsistencies have encouraged the use of
third-party date and time libraries, such as Joda-Time. For these reasons Oracle decided to
provide high-quality date and time support in the native Java API. As a result, Java 8 integrates
many of the Joda-Time features in the java.time package.
In this chapter, we explore the features introduced by the new Date and Time API. We start with
basic use cases such as creating dates and times that are suitable to be used by both humans and
machines, and gradually explore more advanced applications of the new Date and Time API, like
manipulating, parsing, and printing date-time objects and working with different time zones
and alternative calendars.
12.1. LocalDate, LocalTime, Instant, Duration, and Period
Let's start by exploring how to create simple dates and intervals. The java.time package includes
many new classes to help you: LocalDate, LocalTime, LocalDateTime, Instant, Duration, and
Period.
12.1.1. Working with LocalDate and LocalTime
The class LocalDate is probably the first one you'll come across when you start using the new
Date and Time API. An instance of this class is an immutable object representing just a plain
date without the time of day. In particular, it doesn't carry any information about the time zone.
You can create a LocalDate instance using the of static factory method. A LocalDate instance
provides many methods to read its most commonly used values such as year, month, day of the
week, and so on, as shown in the listing that follows.
 
Search WWH ::




Custom Search