The old, much-derided Date and Calendar classes have always been confusing and difficult to use properly, particularly in
a multi-threaded context. JodaTime has long been a popular alternative, but now an even better option is built-in. Java 8's JSR 310
implementation offers specific classes for:
| Class | Use for |
|---|---|
| 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 |
| OffsetDate | a date with an offset such as +02:00, without time of day, 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 |
| YearMonth | a year and month |
| MonthDay | month and day |
| Year/MonthOfDay/DayOfWeek/... | classes for the important fields |
| DateTimeFields | stores a map of field-value pairs which may be invalid |
| Calendrical | access to the low-level API |
| Period | a descriptive amount of time, such as "2 months and 3 days" |
Date now = new Date(); // Noncompliant
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar christmas = Calendar.getInstance(); // Noncompliant
christmas.setTime(df.parse("25.12.2020"));
LocalDate now = LocalDate.now(); // gets calendar date. no time component LocalTime now2 = LocalTime.now(); // gets current time. no date component LocalDate christmas = LocalDate.of(2020,12,25);