The java.time package is a modern date-time framework that debuted in Java 8, defined by JSR 310, supplanting the java.util.Date and .Calendar classes. Inspired by Joda-Time, but re-architected. It uses the ISO 8601 standard as the default for parsing and generating strings and includes classes to represent date-only, time-of-day-only, and span-of-time values.
Instant
A numeric timestamp, stored with nanosecond resolution. Useful for capturing a point in time, similar to System.currentTimeMillis()
. Instant is the closest equivalent class to java.util.Date
. The instant when printed looks like 2000-12-01T12:30:00.000Z
.
LocalDate
A date without a time, offset or time zone. Useful for storing a birthday for example. The date when printed looks like 2000-12-01
.
LocalTime
A time without a date, offset or time zone. Useful for storing store hours for example. The time when printed looks like 12:30:00.000
.
LocalDateTime
A date and time without the offset or time zone. The date and time when printed looks like 2000-12-01T12:30:00.000
.
ZonedDateTime
A date and time with offset and time zone. Useful for performing calculations that take into account the time zone like America/New_York
. ZonedDateTime
is the closest equivalent class to java.util.GregorianCalendar. The date and time when printed looks like 2000-12-01T12:30:00.000-05:00[America/New_York]
It is recommended whenever possible, to use simpler classes without a time zone to model the domain, like LocalDate
, LocalTime
and LocalDateTime
. The widespread use of time zones tends to add considerable complexity to an application. Many applications can use the simpler classes, with the time zone added only at the user interface layer. Other notable classes in the Java Time API are:
Clock
A clock providing access to the current instant, date and time using a time zone. A clock can be used instead of System.currentTimeMillis()
and TimeZone.getDefault()
. Although all key date and time classes have a now()
factory method that uses the system clock, the primary purpose of this abstraction is to allow alternate clocks to be injected, which can greatly simplify testing.
Duration
A duration between two instants on the time-line, stored with nanosecond resolution. This class models a duration of time and is not tied to any instant. The model is directed, meaning that the duration can be negative. The duration when printed looks like PT3600S
.
Period
A period of time expressed in units meaningful to humans, such as '1 Year, 2 Months and 3 Days'. The model is directed, meaning that individual parts of the period may be negative. The period when printed looks like P1Y2M3D
.
ZoneId
A time zone ID, such as America/New_York
.
ZoneOffset
A time zone offset from Greenwich/UTC, such as +02:00.
Documentation
Joda-Time
For similar usage pre-Java 8, see Joda-Time Library: