Date and Time API (Java)
An overview of the Java Date and Time API
Date and Time API basics
Java 1.0 had Date
, most methods deprecated with introduction of Calendar
in Java 1.1. Still not perfect (sometimes awkward API, didn't deal with leap seconds, ...) -> the recommendation used to be to use a library like Joda Time instead.
Java 8 introduced a new Data and Time API under java.time
, which solves a lot of the issues with the older solutions.
Some key points:
- All instances of
java.time
objects are immutable (operations that change dates or times return new objects) - A day has exactly 86400 seconds (leap seconds are dealt with by making seconds last a little bit longer)
Instants and Durations
Instant
: represents a point on the time line
Duration
: represents the amount of time between two instants
Computations with durations:
- Option 1: use methods directly on durations
- Option 2: convert to nanoseconds
- Note that a long of nanoseconds doesn't allow you to use the entire range of a
Duration
, but it a long can hold almost 300 years worth of nanoseconds
- Note that a long of nanoseconds doesn't allow you to use the entire range of a
Local dates and time
Local date/time: has a date and/or time of day, but no time zone information
Example use cases:
- Someone's birthday (this refers to a certain calendar date, but not to a precise instant on the time line)
- Calculations with date and time when you want to ignore time zones and don't want daylight savings time to be taken into account
- Example: a meeting that is at 10:00 every 7 days (regardless of daylight savings time)
- Note: you can also ignore daylight savings time when working with zoned times, see below
Local dates
Note: methods adjusting dates don't throw exceptions if the result would be invalid but adjust it to a valid date instead!
Temporal adjusters
Example: compute first Tuesday of a month
Local time
Zoned time
Zoned time: date and time plus time zone information
- Represents particular instant in time
- When performing calculations or transforming between time zones, daylight savings time and time zone rules are taken into account
Note: there is also OffsetDateTime
, which uses a fixed offset from UTC. This is useful for some technical applications like network protocols. For dealing with human time, ZonedDateTime
is typically the best option.
Formatting and parsing dates
The DateTimeFormatter
class now replaces the old DateTimeFormat
(you can still call toFormat()
on a DateTimeFormatter
to get a legacy DateTimeFormat
)
Resources
- Core Java SE 9 for the Impatient (book by Cay S. Horstmann)