Friday, January 27, 2017

Java 8: Working with date and time simplified

Parsing date strings, comparing dates with Calendar and Date are cumbersome and often hesitate working on these tasks unless we use a third party library like joda time.

With java 8 new api under java.time package, common tasks such as parsing dates in string format, comparing dates and finding number of days between two dates has become very easy and become fun to do.

LocalDate has plenty of methods to parse a date in different formats. The general purpose date formats that are used can be specified using DateTimeFormatter constants. LocalDate has many more utility methods to simplify most useful tasks. It has methods to compare two dates, one can check if a date is before a given date or after the given date or they both are equal.

Another great addition to java.time package is ChronoUnit, which is an enum with set of date and time related units providing functions to manipulate a date, time or date-time.

The below code snippet shows you all of these in action. As one can see the code to perform all those tasks mentioned above become tiny.