The old, much-derided Date and Calendar classes have always been confusing and error-prone, particularly in a
multi-threaded context. The JodaTime library has long been a popular alternative, but it is also considered outdated. Starting from Java SE 8, the
built-in java.time (JSR-310) API provides a modern, immutable, and thread-safe framework that addresses these long-standing design
flaws.
Note: While Joda-Time remains the standard for handling date and time in java versions prior to 8, users of newer versions should
migrate to the java.time API.
The java.time package offers specific classes for:
| Class | Use for |
|---|---|
|
Instant |
a timestamp |
|
LocalDate |
a date, without time of day, offset, or zone |
|
LocalTime |
the time of day, without date, offset, or zone |
|
LocalDateTime |
the date and time, without offset, or zone |
|
OffsetTime |
the time of day with an offset such as +02:00, without date, or zone |
|
OffsetDateTime |
the date and time with an offset such as +02:00, without a zone |
|
ZonedDateTime |
the date and time with a time zone and offset |
|
Year |
a year |
|
YearMonth |
a year and month |
|
MonthDay |
month and day |
|
Month/DayOfWeek |
enum classes for date fields |
|
Period |
a date-based amount of time, such as "2 months and 3 days" |
|
Duration |
a time-based amount of time, such as "34.5 seconds" |
|
Clock |
a clock providing access to the current instant, date and time |
Use the java.time API instead of java.util.Calendar, java.util.Date or JodaTime.
Use of java.util.Date or java.util.Calendar
Date now = new Date(); // Noncompliant
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar christmas = Calendar.getInstance(); // Noncompliant
christmas.setTime(df.parse("25.12.2020"));
Use of Joda-Time
DateTime dateTime = new DateTime(); // Noncompliant
LocalDate nowUTC = LocalDate.now(ZoneOffset.UTC); // gets current date in UTC
LocalDate christmas = LocalDate.of(2020, Month.DECEMBER,25); // create date from year/month/day
ZonedDateTime nowParis = ZonedDateTime.now(ZoneId.of("Europe/Paris")); // get current time in Paris with time-zone information