DateTime API in Java 8 has overcome many shortcomings of older java.util.Date and java.util.Calendar. As there were many issues with the older Date and Calendar API. So now let us see how this java 8 DateTime API resolve the issues and how it provides the better support in JDK core.
Issues in Existing Date/Time APIs :
- Thread Safety.
- Zoned Date and Time.
- Design and Easiness.
Core Idea of Java 8 DateTime API :
The above-mentioned issues are resolved by the Java 8 DateTime API. Following three points will explain how Java 8 DateTime API resolved the issues of Existing java formatter.
- Immutable-value classes: The main issue in the existing java formatter is that they are not thread-safe. Java 8 DateTime API resolve this issues by ensuring that its core classes are immutable and represent the well-defined values.
- Domain-Driven Design: In this new API, classes are more specific, that represent different use cases for Date and Time closely. Basically, new API focussed on Domain-Driven Design and offers long-term benefits around clarity and understandability.
- Chronologies Issues: New API allows developers to use different zone calendering without any burden. There is no need to put any extra effort into doing so.
Local Date :
It represents a date in ISO format without time. It can be used to store dates such as birthdays or any specific occasions. Simply an instance of current date can be created by:
A local date with some specific day, month and year can be generated using of a method in the following way:
Local Time :
It represents a time without Date. Similarly to above-explained LocalDate, LocalTime can also be instantiated as:
Local Date/Time provide many methods that make the developer easy to code and optimize code in terms of operation related to Date and Time. Most commonly used methods are as follows:
- getMonth() and many more.
So the below code will tell us how we can use the methods of Date/Time API.
Zoned DateTime API :
In Java 8 we have a very good feature that if we have to deal with time zone specific date and time, zoneId is an identifier which is available in java.time.zoneId and can be used to represent any zone in the world.