September 27, 2016

Java 8 Date and Time API [Quick Introduction]

Along with new language features like lambda expressions and streams, Java 8 has also introduced a new concept to deal with dates and times. Working with dates and times prior to Java 8 was a little tricky and cumbersome, which led to the popularization of third-party time libraries like Joda-Time. Even for those starting to learn Java with version 8, it is still important to be able to understand the code written the old way. In this article, we will examine the core differences between the old and new way.

First of all, in order to use the new classes, import the java.time package like this:
 import java.time.*;  

Creating Date and Time Objects

One of the problems with the old API was a lack of ability to specify just the date - no time. The Date class represented both date and time.
The new library contains several options to be chosen based on what is required:
  • LocalDate - holds just a date - no time or time zone.
  • LocalTime - holds just a time - no date or time zone.
  • LocalDateTime - comprises a date and time - no time zone.
  • ZonedDateTime - comprises a date, time, and time zone.
Each option has private constructors to make you use one of the factory static methods, for example:
 LocalTime time = LocalTime.now(); //current time in the default time zone  
 LocalDate date = LocalDate.parse("2016-08-20"); //from a String  
 LocalDateTime dateTime = LocalDateTime.of(2016, Month.JULY, 14, 16, 40); //from values  
 ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.of("Europe/Berlin"));  

Let's compare the old and new way of creating an object representing 28 August, 2016. Before Java 8, it was presented as:
 Calendar c = Calendar.getInstance();  
 c.set(2016, 7, 28); //or using constant: c.set(2016, Calendar.AUGUST, 28);   
 Date date = c.getTime();  

Personally, I found using 7 to represent August very confusing, because month indices were 0 based instead of 1 based. Java 8, on the other hand, counts months starting from 1, so the number of the month is the same as when writing the date in real life. Or, even better, just use the enum Month.AUGUST:
 LocalDate date = LocalDate.of(2016, 8, 28); //or alternatively:  LocalDate.of(2016, Month.AUGUST, 28);  

And what happens if an invalid number is passed through when creating a date object? The answer is that an unchecked DateTimeException is thrown:
 LocalDate.of(2016,Month.AUGUST,32); //throws DateTimeException  

Manipulating Date and Time Objects


Next, let's have a look at how to add or even "remove from" a date. The date and time classes in Java 8 are immutable, making it possible to chain the methods:
 LocalDateTime dateTime = LocalDateTime.of(2016, Month.JANUARY, 3, 8, 10);  
     LocalDateTime result = dateTime  
         .plusYears(2)  
         .plusMonths(3)  
         .minusDays(1)  
         .minusHours(2)  
         .plusMinutes(10);  
     System.out.println(result); //prints 2018-04-02T06:20  

As seen here, the method names are fairly self-explanatory. The advantages of the new API are clear when studying the following example which demonstrates the old way of adding 1 hour to a date:
 public static Date addOneHour(Date date) {  
     Calendar calendar = Calendar.getInstance();  
     calendar.setTime(date);  
     calendar.add(Calendar.HOUR,1);  
     return calendar.getTime();  
 }  

Last but not least, be careful about when to employ each method. For example, using the plusMinutes() method on a  LocalDate object cannot be used because LocalDate does not contain time.

Conclusion

This article examined the new Date/Time API introduced by Java 8. It has not covered all the features the new API has to offer by any means.

In summary, the biggest advantage of the new API is that it is stateless; all its core classes are immutable, so it is a lot easier for developers to build thread-safe applications.

3 comments:

  1. Here at this site really the fastidious material collection so that everybody can enjoy a lot.
    go to website

    ReplyDelete
  2. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
    browse this site

    ReplyDelete