New Date-Time API in Java 8
New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API :
- Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn’t have setter methods.
- Less operations : In old API there are only few date operations but the new API provides us with many date operations.
Java 8 under the package java.time introduced a new date-time API, most important classes among them are :
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Local : Simplified date-time API with no complexity of timezone handling.
- Zoned : Specialized date-time API to deal with various timezones.
- LocalDate/LocatTime and LocalDateTime API : Use it when time zones are NOT required.
the current date is 2021-09-23 the current time is 20:52:39.954238 current date and time : 2021-09-23T20:52:39.956909 in formatted manner 23-09-2021 20:52:39 Month : SEPTEMBER day : 23 seconds : 39 the republic day :1950-01-26 specific date with current time : 2016-09-24T20:52:39.956909
- Zoned date-time API : Use it when time zones are to be considered
formatted current Date and Time : 09-04-2018 06:21:13 the current zone is Etc/UTC tokyo time zone is 2018-04-09T15:21:13.220+09:00[Asia/Tokyo] formatted tokyo time zone 09-04-2018 15:21:13
- Period and Duration classes :
Period : It deals with date based amount of time.
Duration : It deals with time based amount of time.
gap between dates is a period of P6Y6M25D the current time is 18:34:24.813548 after adding five hours of duration 23:34:24.813548 duration gap between time1 & time2 is PT-5H
- ChronoUnits Enum : java.time.temporal.ChronoUnit enum is added in Java 8 to replace integer values used in old API to represent day, month etc.
current date is :2018-04-09 next to next year is 2020-04-09 the next month is 2018-05-09 next week is 2018-04-16 20 years after today 2038-04-09
- TemporalAdjuster : It is used to perform various date related operations.
the current date is 2021-07-09 firstDayOfNextMonth : 2021-08-01 next saturday from now is 2021-07-10 firstDayOfMonth : 2021-07-01 lastDayOfMonth : 2021-07-31