2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
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:
2021-06-03 16:43:28 +02:00
[frame=all]
[cols="^1,^1"]
|===
|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"
|===
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Date now = new Date(); // Noncompliant
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar christmas = Calendar.getInstance(); // Noncompliant
christmas.setTime(df.parse("25.12.2020"));
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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);
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Use the Java 8 Date and Time API instead.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 12 Oct 2014, 21:55:53 Ann Campbell wrote:
\[~freddy.mallet] & [~nicolas.peru] I'm not wild about the title. Suggestions welcome!
=== on 13 Oct 2014, 12:56:46 Nicolas Peru wrote:
\[~ann.campbell.2] What about : classes from "java.time" package should be used for date and time. ?
=== on 14 Oct 2014, 14:17:56 Ann Campbell wrote:
Thanks [~nicolas.peru]. Updated.
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]