The new date/time API in Java 8 is
contained in the java.time package. If you're familiar with Joda Time, it will
be really easy to pick up. Actually, I think it's so well-designed that even
people who have never heard of Joda Time should find it easy to pick up.
Almost everything in the API is
immutable, including the value types and the formatters. No more worrying about
exposing Date fields or dealing with thread-local date formatters.
The intermingling with the legacy
date/time API is minimal. It was a clean break:
The new API prefers enums over integer
constants for things like months and days of the week.
So, what's in it? The package-level
javadocs do an excellent job of explaining the additional types. I'll give a
brief rundown of some noteworthy parts.
Extremely useful value types:
- LocalDateTime, LocalDate, LocalTime
- Year, Month, YearMonth, MonthDay, DayOfWeek (ok, maybe Year is a little
less useful than the others)
Less useful value types:
- Instant - similar to java.util.Date
- ZonedDateTime, ZoneId - for when time zones are important
- OffsetDateTime, OffsetTime, ZoneOffset - for dealing with offsets
from UTC
- Duration, Period - although if you're trying to
find the amount of time between two dates, you might be looking for
ChronoUnit instead (see below)
Other useful types:
- DateTimeFormatter - for converting
datetime objects to strings
- ChronoUnit - for figuring out the
amount of time bewteen two points, e.g. ChronoUnit.DAYS.between(t1,
t2)
- TemporalAdjuster - e.g. date.with(TemporalAdjuster.firstDayOfMonth())
The new value types are, for the most
part, supported by JDBC. There are minor exceptions, such as ZonedDateTime
which has no counterpart in SQL.
No comments:
Post a Comment