Java Reference
In-Depth Information
P12Y // A duration of 12 years
PT15:30 // A duration of 15 hours and 30 minutes
PT20S // A duration of 20 seconds
P4Y2MT30M // A duration of 4 years 2 months and 30 minutes
■
the Date-time api provides
Duration
and
Period
classes to deal with an amount of time. a
Duration
represents an amount of time on machine-scale timeline. a
Period
represents an amount of time on human-scale timeline.
Tip
Exploring the New Date-Time API
At first, exploring the Date-Time API is intimidating as it contains many classes with numerous methods. Learning the
naming convention of methods will help understand the API tremendously. The Date-Time API has been designed
carefully to keep the names of classes and their methods consistent and intuitive. Methods starting with the same
prefix do the similar work. For example, a
of()
method in a class is used as a static factory method to create an object
of that class.
All classes, interfaces, and enums for the Date-Time API are in the
java.time
package and four of its
subpackages:
•
java.time
contains frequently used classes.
LocalDate
,
LocalTime
,
LocalDateTime
,
ZonedDateTime
,
Period
,
Duration
, and
Instant
classes are in this package. Classes in this
package are based on ISO standards.
•
java.time.chrono
contains classes supporting non-ISO calendar systems, for example,
Hijrah calendar, ThaiBuddhist calendar, etc.
•
java.time.format
contains classes for formatting and parsing dates and times.
•
java.time.temporal
contains classes for accessing components of dates and times. It also
contains classes that acts like date-time adjusters.
java.time.zone
contains classes supporting time zones and zone rules.
The following sections explain the prefixes used in method names in the Date-Time API with their meanings
and examples.
•
The ofXXX( ) Methods
Classes in the Date-Time API do not provide public constructors to create their objects. They let you create objects
through static factory methods named
ofXXX()
. The following snippet of code shows how to create objects of the
LocalDate
class:
LocalDate ld1 = LocalDate.of(2012, 5, 2); // 2012-05-02
LocalDate ld2 = LocalDate.of(2012, Month.JULY, 4); // 2012-07-04
LocalDate ld3 = LocalDate.ofEpochDay(2002); // 1975-06-26
LocalDate ld4 = LocalDate.ofYearDay(2014, 40); // 2014-02-09