Java 8

How to find date time differences in Java 8

In Java8, we can use following classes to find date time differences :

  • Period
  • Duration
  • ChronoUnit

 

Period

We can use Period class to calculate difference in year, month, days between two Dates.

Here is an example of using Period class methods getYears(), getMonths() and getDays() to calculate age of a person.

package com.topjavatutorial;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

public class DateUtil {

  public static void main(String[] args) {
    LocalDate today = LocalDate.now();
    System.out.println("Today : " + today);
    LocalDate birthDate = LocalDate.of(2012, Month.JANUARY, 1);
    System.out.println("BirthDate : " + birthDate);

    Period p = Period.between(birthDate, today);
    System.out.printf("Age : %d Years %d Months %d Days", p.getYears(),
        p.getMonths(), p.getDays());
  }
}

Output :

Today : 2017-03-20
BirthDate : 2012-01-01
Age : 5 Years 2 Months 19 Days
 

Duration

Duration class provides methods to measure an amount of time using time-based values like seconds, nanoseconds.

package com.topjavatutorial;

import java.time.Duration;
import java.time.Instant;

public class DateUtil {

  public static void main(String[] args) {
    Instant inst1 = Instant.now();
    System.out.println("Inst1 : " + inst1);
    Instant inst2 = inst1.plus(Duration.ofSeconds(10));
    System.out.println("Inst2 : " + inst2);
    
    System.out.println("Difference in milliseconds : "
        + Duration.between(inst1, inst2).toMillis());
    
    System.out.println("Difference in seconds : "
        + Duration.between(inst1, inst2).getSeconds());

  }
}

Output :

Inst1 : 2017-03-20T05:14:14.777Z
Inst2 : 2017-03-20T05:14:24.777Z
Difference in milliseconds : 10000
Difference in seconds : 10

 

ChronoUnit

ChronoUnit class is useful to measure an amount of time in a single unit of time only, such as days or seconds.

Here is an example of using ChronoUnit.between() method to find difference between two dates.

package com.topjavatutorial;

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

public class DateUtil {

  public static void main(String[] args) {

    LocalDate startDate = LocalDate.of(2012, Month.JANUARY, 1);
    System.out.println("Start Date  : " + startDate);

    LocalDate endDate = LocalDate.of(2017, Month.MARCH, 15);
    System.out.println("End Date : " + endDate);

    long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);
    System.out.println("Difference between the two dates in Days : "
        + daysDiff);
  }

}

Output :

Start Date : 2012-01-01
End Date : 2017-03-15
Difference between the two dates in Days : 1900
 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags