New Date and Time API in Java 8

Java 8 introduces a brand new Date and Time API that fixes many problems typical of the old Date and Calendar classes. The new Date and Time API was designed around two main principles:

Domain-driven design

The new Date and Time API precisely models various notions of date and time by introducing new classes to represent them. For example, you can use the class Period to represent a value like “2 months and 3 days” and ZonedDateTime to represent a date–time with a time zone. Each class provides domainspecific methods that adopt a fluent style. Consequently, you can chain methods to write more readable code. For example, the following code shows how to create a new LocalDateTime object and add 2 hours and 30 minutes:

LocatedDateTime coffeeBreak = LocalDateTime.now().plusHours(2).plusMinutes(30); 

Immutability:  One of the problems with Date and Calendar is that they weren’t thread-safe. In addition, developers using dates as part of their API can accidentally update values unexpectedly. To prevent these potential bugs, the classes in the new Date and Time API are all immutable. In other words, you can’t change an object’s state in the new Date and Time API. Instead, you use a method to return a new object with an updated value.

The following code exemplifies various methods available in the new Date and Time API:

ZoneId london = ZoneId.of("Europe/London"); 
LocalDate july4 = LocalDate.of(2014, Month.JULY, 4); 
LocalTime early = LocalTime.parse("08:45"); 
ZonedDateTime flightDeparture = ZonedDateTime.of(july4, early, london); 
System.out.println(flightDeparture);
LocalTime from = LocalTime.from(flightDeparture); 
System.out.println(from);
ZonedDateTime touchDown = ZonedDateTime.of(july4,LocalTime.of (11, 35),ZoneId.of("Europe/Stockholm")); 
Duration flightLength = Duration.between(flightDeparture, touchDown); 
System.out.println(flightLength);
// How long have I been in continental Europe? 
ZonedDateTime now = ZonedDateTime.now(); 
Duration timeHere = Duration.between(touchDown, now); 
System.out.println(timeHere);

This code will produce an output similar to this:

2015-07-04T08:45+01:00[Europe/London] 08:45 PT1H50M PT269H46M55.736S 

 

Java-8 12

FOLLOW US ON LinkedIn



Explore Tutu'rself