Let's have a look at the all new Date and Time API in Java 8. It is a complete replacement for the old java.util.Date and Calendar classes.
The new API in Java8 was mainly inspired by the popular open source date library JodaTime. But the implementation itself is said to be 100% new written code.
Reasons for a new API are obvious when you had the pleasure to work with java.util.Date & Calendar:
- java.util.Date is mutable.
- Calendar API was really heavy to work with (lots of code for nothing)
- No built-in support to express periods and durations
The benefits of the new API:
- Immutable classes
- Easy to use with a fluent API
- Supports periods and durations
- Data types for different time precisions (e.g. Year, LocalDate, LocalDateTime)
Working with the API
Instant is the closest type in comparison to the java.util.Date(). It holds the seconds from 1970-01-01T00:00:00Z.
Instant.now(); // e.g. 1396105152537
The LocalDate represents a simple date (year, month, day) without time information.
LocalDate.now(); // e.g. 2014-03-27
LocalDateTime holds time information (hour, minute, second) additionally.
LocalDateTime.now(); // e.g. 2014-03-27 16:00:00
The Local* classes don't hold timezone information.
ZonedDateTime / OffestDateTime
This two classes should be used if you care about different timezones.
Period / Duration
This two classes should be used to work with an amount of time. Periods messaure the amount in years, months and days. Durations messaure the amount in hours, minutes and seconds.
Duration.between(Instant.now(), Instant.now().plusHours(1)) // => 1 hour Period.between(LocalDate.now(), LocalDate.now().plusMonths(1)) // => 1 month
You can also use the ChronoUnit Enumeration to get the difference between to dates.
ChronoUnits.DAYS.between(LocalDate.now(), LocalDate.now().plusMonths(1)) // => ~30 days
The new Date and time is not compatible to the old Date and Calendar classes. To interop between this two implementations, convenience methods are provided:
new java.util.Date(...).toInstant(); Instant.now().toDate();
Date Time API without Java 8
If you are using Java 7 and are currently not able to switch to Java 8, you might be interested in the following project:
A backport of JSR-310 named ThreeTen is available for Java 7.
The new Java Date and Time API is much more better compared to the old one. This post was just an incomplete rush over some basic functionality. I'd recommend the Java Tutorial about the new Date and Time API.