Java SE 8 had refactored the date time implementations to improve internal consistency and readability without changing its function. Java prior versions has been missing a consistent approach for Date and Time API which led the developers to mix up while using the API. Java 8 Date and Time API is one of the most sought after change for developers.
Let’s have a look at some of the changes to Date and Time API.
- Classes in the new Date Time API are immutable and good for multi threaded environments.
- It defines separate classes for Date, Time, DateTime, Timestamp, Timezone etc. and separates clearly between human readable date time and machine time (unix timestamp).
- 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 new Date Time API classes comes with methods to perform common tasks, such as plus, minus, format, parsing, getting separate part in date/time etc.
Local Date : 2014-06-30
Local Time : 10:54:20.540
All classes of the Java 8 Date/Time API are located within the java.time package. The class we want to look at is java.time.LocalDate for Date and java.time.LocalTime for time. A LocalDate represents a year-month-day date without time. A LocalTime represents a hour-minute-second time. To have Date with time look at java.time.LocalDateTime Class. You can check above example to see how the date and time are represented by this classes. Now let’s have few examples of how to defines custom date , time and timezones as follows:
UseCase #1 : 2013-03-01
UseCase #2 : 2010-04-10
Current Date/Time : 2014-06-30T11:25:19.035
UseCase #3 : 2014-12-24T12:00
UseCase #4 : 2014-06-30T13:55:19.035
Let’s look at some other features of Date and Time API such as Leap Year, Period , Duration , Formatting , parsing and conversions.
Leap Year : 2012
John is 27 Years 7 Months 21 Days Old.
Difference is hours 15
Basic ISO Format : 20140630
ISO Week Date : 2014-W27-1
ISO Date Time : 2014-06-30T12:03:08.61
Custom Pattern : 30/06/2014
Turkish Date :30. Haziran 2014
ISO Date : 2013-10-22
ISO Week Date : 2012-10-09
Custom Pattern : 2011-01-20
Java 8 provides a very rich API for working with date and time located in the java.time package. The API can completely replace old classes like java.util.Date or java.util.Calendar with newer, more flexible classes.