Java 8

Java8 – New Date/Time API

With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time API.

  1. 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.
  2. 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.
  3. 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 introduces a new date-time API under the package java.time. Following are some of the important classes introduced in java.time package.

  1. Local − Simplified date-time API with no complexity of timezone handling.
  2. Zoned − Specialized date-time API to deal with various timezones.

Local Date-Time API

LocalDate/LocalTime and LocalDateTime classes simplify the development where timezones are not required. Let’s see them in action.

Create the following java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testLocalDateTime();
   }
	
   public void testLocalDateTime() {
      // 1. Get the current date and time
      LocalDateTime currentTime = LocalDateTime.now();
      System.out.println("Current Local DateTime: " + currentTime);
		
      LocalDate date1 = currentTime.toLocalDate();
      System.out.println("Local Date1: " + date1);
		
      Month month = currentTime.getMonth();
      int day = currentTime.getDayOfMonth();
      int seconds = currentTime.getSecond();
		
      System.out.println("Month: " + month +" day: " + day +" seconds: " + seconds);
		
      LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2018);
      System.out.println("LocalDateTime date2: " + date2);
		
      // 2. Date is 12 december 2014
      LocalDate date3 = LocalDate.of(2018, Month.DECEMBER, 12);
      System.out.println("LocalDate date3: " + date3);
		
      // 3. Time is 22 hour 15 minutes
      LocalTime date4 = LocalTime.of(22, 15);
      System.out.println("LocalTime date4: " + date4);
		
      // 4. parse a string
      LocalTime date5 = LocalTime.parse("20:15:30");
      System.out.println("LocalTime date5: " + date5);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following output −

Current Local DateTime: 2022-10-04T14:15:02.013
Local Date1: 2022-10-04
Month: OCTOBER day: 4 seconds: 2
LocalDateTime date2: 2018-10-10T14:15:02.013
LocalDate date3: 2018-12-12
LocalTime date4: 22:15
LocalTime date5: 20:15:30

Zoned Date-Time API

Zoned date-time API is to be used when time zone is to be considered. Let us see them in action.

Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.ZonedDateTime;
import java.time.ZoneId;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testZonedDateTime();
   }
	
   public void testZonedDateTime() {
      // 1. Get the current date and time
      ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Calcutta]");
      System.out.println("ZonedDateTime: " + date1);
	  
      // 2. Get specific zone id
      ZoneId id = ZoneId.of("Europe/Paris");
      System.out.println("ZoneId: " + id);
	
      // 3. Get default zone id
      ZoneId currentZone = ZoneId.systemDefault();
      System.out.println("CurrentZone: " + currentZone);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following output −

ZonedDateTime: 2007-12-03T10:15:30+05:30[Asia/Calcutta]
ZoneId: Europe/Paris
CurrentZone: Asia/Calcutta

Chrono Units Enum

java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values used in old API to represent day, month, etc. Let us see them in action.

Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testChromoUnits();
   }
	
   public void testChromoUnits() {
      // 1. Get the current date
      LocalDate today = LocalDate.now();
      System.out.println("Current date: " + today);
		
      // 2. add 1 week to the current date
      LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
      System.out.println("Next week: " + nextWeek);
		
      // 3. add 1 month to the current date
      LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
      System.out.println("Next month: " + nextMonth);
		
      // 4. add 1 year to the current date
      LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
      System.out.println("Next year: " + nextYear);
		
      // 5. add 10 years to the current date
      LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
      System.out.println("Date after ten year: " + nextDecade);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following result −

Current date: 2022-10-04
Next week: 2022-10-11
Next month: 2022-11-04
Next year: 2023-10-04
Date after ten year: 2032-10-04

Period and Duration

With Java 8, two specialized classes are introduced to deal with the time differences.

  1. Period − It deals with date based amount of time.
  2. Duration − It deals with time based amount of time.

Let us see them in action.

Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Duration;
import java.time.Period;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testPeriod();
      java8DateTime.testDuration();
   }
	
   public void testPeriod() {
      // 1. Get the current date
      LocalDate date1 = LocalDate.now();
      System.out.println("Current date: " + date1);
		
      // 2. 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() {
	  // 1. Get the current time
      LocalTime time1 = LocalTime.now();
      Duration twoHours = Duration.ofHours(2);
		
      // 2. Add 2 hours to the current time
      LocalTime time2 = time1.plus(twoHours);
      Duration duration = Duration.between(time1, time2);
		
      System.out.println("Duration: " + duration);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following output −

Current date: 2022-10-04
Next month: 2022-11-04
Period: P-1M
Duration: PT2H

Temporal Adjusters

TemporalAdjuster is used to perform the date mathematics. For example, get the “Second Saturday of the Month” or “Next Tuesday”. Let us see them in action.

Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testAdjusters();
   }
	
   public void testAdjusters() {
      // 1. Get the current date
      LocalDate date1 = LocalDate.now();
      System.out.println("Current date: " + date1);
		
      // 2. get the next Wednesday
      LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
      System.out.println("Next Wednesday on : " + nextTuesday);
		
      // 3. get the second Sunday of next month
      LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);
      LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(
         DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
      System.out.println("Second Sunday on : " + secondSaturday);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following result −

Current date: 2022-10-04
Next Wednesday on : 2022-10-05
Second Sunday on : 2022-10-09

Backward Compatibility

A toInstant() method is added to the original Date and Calendar objects, which can be used to convert them to the new Date-Time API. Use an ofInstant(Insant,ZoneId) method to get a LocalDateTime or ZonedDateTime object. Let us see them in action.

Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.

Java8DateTime.java
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;

public class Java8DateTime {

   public static void main(String args[]) {
      Java8DateTime java8DateTime = new Java8DateTime();
      java8DateTime.testBackwardCompatability();
   }
	
   public void testBackwardCompatability() {
      // 1. Get the current date
      Date currentDate = new Date();
      System.out.println("Current date: " + currentDate);
		
      // 2. Get the instant of current date in terms of milliseconds
      Instant now = currentDate.toInstant();
      ZoneId currentZone = ZoneId.systemDefault();
		
      LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
      System.out.println("Local date: " + localDateTime);
		
      ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
      System.out.println("Zoned date: " + zonedDateTime);
   }
}

Output

Compile the class using javac compiler as follows −

C:\hitechpoints\workspace\java8\src>javac Java8DateTime.java

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java8\src>java Java8DateTime

It should produce the following output −

Current date: Tue Oct 04 14:38:37 IST 2022
Local date: 2022-10-04T14:38:37.741
Zoned date: 2022-10-04T14:38:37.741+05:30[Asia/Calcutta]

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs