New Date-Time API in Java 8

Java 8Object Oriented ProgrammingProgramming

The new Date-Time API introduced in Java 8 to overcome the flaws in the existing  java.util.Date and java.util.Calendar. Following were the issues with the old Date-Time API −

  • Not thread safe − java.util.Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods.

  • Poor design − Default Date starts from 1900, month starts from 1, and day starts from 0, so no uniformity. The old API had less direct methods for date operations. The new API provides numerous utility methods for such operations.

  • Difficult time zone handling − Developers had to write a lot of code to deal with timezone issues. The new API has been developed keeping domain-specific design in mind.

Java 8 introduced new classes in java.time package.

  • Local − Simplified date-time API with no complexity of timezone handling.

  • Zoned − Specialized date-time API to deal with various timezones.

Java 8 also introduced two specialized classes to deal with the time differences.

  • Period − It deals with date based amount of time.

  • Duration − It deals with time based amount of time.

Let us now see an example −

Example

import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Duration;
import java.time.Period;
public class Demo {
   public static void main(String args[]) {
      Demo d = new Demo();
      d.testPeriod();
      d.testDuration();
   }
   public void testPeriod() {
      //Get the current date
      LocalDate date1 = LocalDate.now();
      System.out.println("Current date: " + date1);
      //add 1 month to the current date
      LocalDate date2 = date1.plus(1, ChronoUnit.MONTHS);
      System.out.println("Next month: " + date2);
      Period period = Period.between(date2, date1);
      System.out.println("Period: " + period);
   }
   public void testDuration() {
      LocalTime time1 = LocalTime.now();
      Duration twoHours = Duration.ofHours(2);
      LocalTime time2 = time1.plus(twoHours);
      Duration duration = Duration.between(time1, time2);
      System.out.println("Duration: " + duration);
   }
}

Output

Current date: 2019-09-14
Next month: 2019-10-14
Period: P-1M
Duration: PT2H
raja
Published on 20-Sep-2019 14:45:35
Advertisements