Date Time API is one of the biggest features of Java 8 release. Java was missing a consistent approach for Date and Time from start and Java 8 Date Time API is a welcome addition to the core Java APIs.
Before we start looking at the Java 8 Date Time API, let’s see why do we need a new API for this. There have been several problems with the existing date and time related classes in java, some of them are:
There are some other issues with the methods defined in Date and Calendar classes but above problems make it clear that a robust Date Time API was needed in Java. That’s why Joda Time played a key role as a quality replacement for Java Date Time requirements.
Java 8 Date Time API is JSR-310 implementation. It is designed to overcome all the flaws in the legacy date time implementations. Some of the design principles of new Date Time API are:
Immutability: All the classes in the new Date-Time API are immutable and good for multithreaded environments.
Separation of Concerns: The new API separates clearly between human-readable date time and machine time (Unix timestamp). It defines separate classes for Date, Time, DateTime, Timestamp, Timezone, etc.
Clarity: The methods are clearly defined and perform the same action in all the classes. For example, to get the current instance we have now() method. There are format() and parse() methods defined in all these classes rather than having a separate class for them.
All the classes use Factory Pattern and Strategy Pattern for better handling. Once you have used the methods in one of the classes, working with other classes won’t be hard.
Utility operations: All the new Date-Time API classes come with methods to perform common tasks, such as plus, minus, format, parsing, getting the separate part in date/time, etc.
Extendable: The new Date Time API works on the ISO-8601 calendar system but we can use it with other non-ISO calendars as well.
Java 8 Date Time API consists of following packages.
We have looked into most of the important parts of Java Date Time API. It’s time now to look into most important classes of Date Time API with examples.
LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance.
This class provides an overloaded method for now() where we can pass ZoneId for getting dates in a specific time zone. This class provides the same functionality as java.sql.Date.
LocalDate methods explanation is provided in the comments. When we run this program, we get the following output.
LocalTime is an immutable class whose instance represents a time in the human readable format. It’s default format is hh:mm:ss.zzz. Just like LocalDate, this class provides time zone support and creating instance by passing hour, minute and second as input arguments.
Output:
LocalDateTime is an immutable date-time object that represents a date-time with default format as yyyy-MM-dd-HH-mm-ss.zzz. It provides a factory method that takes LocalDate and LocalTime input arguments to create LocalDateTime instance.
In all the three examples, we have seen that if we provide invalid arguments for creating Date/Time, then it throws java.time.DateTimeException, which is a RuntimeException so we don’t need to explicitly catch it.
We have also seen that we can get Date/Time data by passing ZoneId, you can get the list of supported ZoneId values from its JavaDoc. When we run the above class, we get the following output.
Instant class is used to work with machine readable time format. Instant stores date time in unix timestamp.
Output:
Most of the Date Time principle classes provide various utility methods such as plus/minus days, weeks, months etc. There are some other utility methods for adjusting the date using TemporalAdjuster
and to calculate the period between two dates.
Output:
It’s very common to format date into different formats and then parse a String to get the Date Time objects.
Output:
Legacy Date/Time classes are used in almost all the applications, so having backward compatibility is a must. That’s why there are several utility methods through which we can convert Legacy classes to new classes and vice versa.
Output:
As you can see that legacy TimeZone
and GregorianCalendar
classes toString() methods are too verbose and not user friendly.
I like this new Date Time API a lot. Some of the most used classes will be LocalDate and LocalDateTime. It’s very easy to work with the new classes. And, having similar methods that does a particular job makes it easy to find. It will take some time from moving legacy classes to new Date Time classes, but I believe it will be worth the time and effort.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Very clear explanation - Thanks for sharing.
- Pradeep Tiwari
Hello, Hello I would like to get a fixed schedule ( another class ) and subtract your local schedule , how can I do this ? Thank you!
- Leonardo
great explanation
- Jothimanickam M
How to use LocalDate with JSF Form ? I have a field (inputText or inputMask (dd/mm/yyyy)) that will be filled with a date by User. What i have to do for store this value inserted in an attribute type LocalDate. ?
- Rafael
Great Job Pankanj ! It was in deed a great article !
- Shuba
Hello, I’m a java developer in South Korea. I would like to share this article for my friends. Could I repost this on my website after translating? if it is possible, please send me email. Email : goodmorning0726@gmail.com thanks
- kangddanddan
thanks for this good sharing ! It was in deed a great article !
- fred
Thanks, nice post
- Binh Thanh Nguyen
Nice article
- yellappa
Many thanks for the clear and to the point explanation! That’s exactly what I was looking for.
- Utpal Nandi