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.
Why do we need new Java Date Time API?
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:
- Java Date Time classes are not defined consistently, we have Date Class in both java.util as well as java.sql packages. Again formatting and parsing classes are defined in java.text package.
- java.util.Date contains both date and time values whereas java.sql.Date contains only date value. Having this in java.sql package doesn’t make any sense. Also, both the classes have the same name, which is a very bad design itself.
- There are no clearly defined classes for time, timestamp, formatting, and parsing. We have java.text.DateFormat abstract class for parsing and formatting need. Usually, the SimpleDateFormat class is used for parsing and formatting.
- All the Date classes are mutable, so they are not thread-safe. It’s one of the biggest problems with Java Date and Calendar classes.
- Date class doesn’t provide internationalization, there is no timezone support. So java.util.Calendar and java.util.TimeZone classes were introduced, but they also have all the problems listed above.
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 Design Principles
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.
Date Time API Packages
Java 8 Date Time API consists of following packages.
- java.time: This is the base package of the new Java Date Time API. All the major base classes are part of this package, such as LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration, etc. All of these classes are immutable and thread-safe. Most of the time, these classes will be sufficient for handling common requirements.
- java.time.chrono: This package defines generic APIs for non-ISO calendar systems. We can extend AbstractChronology class to create our own calendar system.
- java.time.format: This package contains classes used for formatting and parsing date-time objects. Most of the time we would not be directly using them because of principle classes in java.time package provides formatting and parsing methods.
- java.time.temporal: This package contains temporal objects and we can use it to find out the specific dates or times related to the date/time objects. For example, we can use these to find out the first or last day of the month. You can identify these methods easily because they always have the format “withXXX”.
- java.time.zone Package: This package contains classes for supporting different time zones and their rules.
Java 8 Date Time API Classes Examples
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.
1. LocalDate
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.
2. LocalTime
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:
3. LocalDateTime
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.
4. Instant
Instant class is used to work with machine readable time format. Instant stores date time in unix timestamp.
Output:
Java 8 Date API Utilities
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:
Java 8 Date Parsing and Formatting
It’s very common to format date into different formats and then parse a String to get the Date Time objects.
Output:
Java Date API Legacy Date Time Support
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.
Conclusion
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.
Source:
https://www.digitalocean.com/community/tutorials/java-8-date-localdate-localdatetime-instant