There is a whole set of date's classes in Java 8:
java.time.LocalDateTime
;java.time.ZonedDateTime
;java.time.Instant
;java.time.OffsetDateTime
;java.sql.Timestamp
;java.util.Date
.I already passed over their JavaDocs and paid attention that all these classes contain all the methods I need. Thus, for the moment, I can select them randomly. But I guess that there is some reason why there are 6 separate classes and each of them is dedicated to the specific purpose.
Technical information & requirements:
String
, which is converted to one of these date formats.My questions:
Using LocalDate, LocalTime and LocalDateTime. The most commonly used classes are LocalDate, LocalTime and LocalDateTime.
SimpleDateFormat: It is a class that is used to format and parse the dates in a predefined manner or user defined pattern. java. util.
util. Date class which represents date without time information and it should be used only when dealing with databases. To conform with the definition of SQL DATE, the millisecond values wrapped by a java. sql.
sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.
Each one of the Date
classes are for specific purposes:
If you want to use your Date in an SQL
/JDBC
context, use the java.sql.Timestamp
.
java.util.Date
is the old Java API, it is not thread safe, you can difficultly handle time zoning, and on the top of all, it is poorly designed: one simple uniformity is that months start from 1 while days start from 0.
java.time.LocalDateTime
is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second, which you need exactly.
java.time.ZonedDateTime
class stores all date and time fields, so you can use it to deal with values like: 27th January 1990 at 15:40.30.123123123 +02:00
in the Europe/Paris time-zone.
To do your task, the ZonedDateTime
class handles conversion from the local time-line of LocalDateTime
to the instant time-line of Instant
(which models a single instantaneous point on the time-line). The difference between the two time-lines, represented by a ZoneOffset
, is the offset from UTC/Greenwich.
To calculate duration and period: there is the java.time.Duration
which is a time-based amount of time, such as '20.5 seconds', and java.time.Period
, which is a date-based amount of time (like: 26 years, 2 months and 2 days).
To get max and min dates, you can use the Java 8 lambdas 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With