What date class should be used in Java 8?

Java 8 has a whole set of date classes:

  • java.time.LocalDateTime ;
  • java.time.ZonedDateTime ;
  • java.time.Instant ;
  • java.time.OffsetDateTime ;
  • java.sql.Timestamp ;
  • java.util.Date .

I already passed my JavaDocs and noticed that all these classes contain all the methods I need. Thus, at the moment I can select them randomly. But I assume that there is some reason why there are 6 separate classes, and each of them is dedicated to a specific purpose.

Technical information and requirements:

  • The input is in String , which is converted to one of these date formats.
  • I do not need to display time zones, but when I compare two dates, it is important to be able to correctly compare the time in New York and in Paris.
  • The exact level is seconds, there is no need to use milliseconds.
  • Required Operations:
    • find the date max / min;
    • sort objects by date;
    • calculate the date and time (the difference between the two dates);
    • insert objects into MongoDB and extract them from db by date (for example, all objects after a certain date).

My questions:

  • What aspects should be considered in order to choose the best format among these four parameters in terms of performance and ease of maintenance?
  • Is there a reason I should avoid some of these date classes?
+9
java date datetime timestamp java-8
source share
1 answer

Each of the Date classes is designed for specific purposes:

  • If you want to use your date in the context of SQL / JDBC , use java.sql.Timestamp .

  • java.util.Date is an old Java API, it is not thread safe, you can hardly handle time zoning, and most importantly, it is poorly designed: one simple uniformity is that the months start at 1 and the days start at 0.

  • java.time.LocalDateTime is an immutable date object that represents a date-time, often seen as year-month-day-hour-minute-second, which you need for sure.

  • java.time.ZonedDateTime class stores all date and time fields, so you can use it to process values ​​such as: 27th January 1990 at 15:40.30.123123123 +02:00 in the Europe / Paris time zone.

To accomplish its task, the ZonedDateTime class handles the conversion from the local LocalDateTime time line to the current Instant time line (which models one instantaneous point on the time line). The difference between the two timelines represented by a ZoneOffset is an offset from UTC / Greenwich.

To calculate the duration and period: there is java.time.Duration , which is a time interval such as "20.5 seconds" and java.time.Period , which is a time based on date (for example: 26 years, 2 months and 2 days).

To get the maximum and minimum dates, you can use Java 8 iambads in something like:

 Date maxDate = list.stream().map(yourInstance -> yourInstance.date).max(Date::compareTo).get(); Date minDate = list.stream().map(yourInstance -> yourInstance.date).min(Date::compareTo).get(); 
+10
source share

All Articles