September 20, 2022

Java Date Difference Program

In this post we’ll see how to calculate date and time difference in Java in terms of Years, months, days and hours, minutes, seconds.

To calculate difference between two dates in Java you can use SimpleDateFormat class though using that involves a lot of manual calculation and it doesn’t take time zones, day light saving into account.

To mitigate these shortcoming a new Date and Time API is added in Java 8 which provides classes to calculate date and time difference using inbuilt methods and also take into consideration time zones, day light saving and leap years while calculating difference.

Difference between two dates Using SimpleDateFormat

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DifferenceDate {
  public static void main(String[] args) {
    try {
      dateDiff("15/08/2019 09:10:05", "04/09/2019 14:22:15", "dd/MM/yyyy HH:mm:ss");
    } catch (ParseException e) {
      // TODO Auto-generated catch block
         e.printStackTrace();
    }
  }
	
  private static void dateDiff(String date1, String date2, String pattern) throws ParseException{
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    Date d1 = sdf.parse(date1);
    Date d2 = sdf.parse(date2);
    long diffInMillis = d2.getTime() - d1.getTime();
    
    long daysDiff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
    
    long hoursDiff = TimeUnit.HOURS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

    long minutesDiff = TimeUnit.MINUTES.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

    long secondsDiff = TimeUnit.SECONDS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000) - (minutesDiff * 60 * 1000), TimeUnit.MILLISECONDS);

    System.out.println(daysDiff + " day(s) " + hoursDiff + " Hour(s) " + minutesDiff + " Minute(s) " + secondsDiff + " Second(s)");
  }
}
Output
20 day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

As you can see using SimpleDateFormat requires lot of manual effort where you need to convert as per the required time unit.

Difference between two dates using Java 8 classes

In the new date and time API in Java 8 there are following classes that can be used for date difference calculation.

  • java.time.Period- A date-based amount of time, supported units of a period are YEARS, MONTHS and DAYS.
  • java.time.Duration- A time-based amount of time. This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours.
  • java.time.temporal.TemporalUnit- TemporalUnit is an interface that represents a unit of date-time, such as Days or Hours.
  • java.time.temporal.ChronoUnit- It is an Enum that implements TemporalUnit interface.

Difference between two dates in terms of years, months, days

Difference between two dates in date-based amount of time can be calculated using Period class.

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

public class DifferenceDate {
  public static void main(String[] args) {
    LocalDate date1 = LocalDate.of(2018, 8, 15);
    LocalDate date2 = LocalDate.of(2019, 9, 4);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDate date1, LocalDate date2){
    Period p = Period.between(date1, date2);		
    System.out.printf("%d Year(s) %d Month(s) %d Day(s)", p.getYears(), p.getMonths(), p.getDays());
  }
}
Output
1 Year(s) 0 Month(s) 20 Day(s)

Difference between two dates in terms of days, hours, minutes, seconds

Difference between two dates in a time-based amount of time can be calculated using Duration class.

public class DifferenceDate {

  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    Duration d = Duration.between(date1, date2);	
    System.out.printf("%d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", d.toDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart());
  }
}
Output
1 Day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

Using both Period and Duration classes to calculate date difference

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;

public class DifferenceDate {
  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2018, 7, 2, 12, 18, 13);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }

  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    Period p = Period.between(date1.toLocalDate(), date2.toLocalDate());
    Duration d = Duration.between(date1, date2);
    System.out.printf("%d Year(s) %d Month(s) %d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", 
        p.getYears(), p.getMonths(), p.getDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart());
  }
}
Output
1 Year(s) 2 Month(s) 2 Day(s) 2 Hour(s) 4 Minute(s) 2 Second(s)

Using ChronoUnit to find difference

If you want the total difference in terms of units then ChronoUnit can also be used.

public class DifferenceDate {

  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    long daysDiff = ChronoUnit.DAYS.between(date1, date2);
    long hoursDiff = ChronoUnit.HOURS.between(date1, date2);
    long minutesDiff = ChronoUnit.MINUTES.between(date1, date2);
    long secondsDiff = ChronoUnit.SECONDS.between(date1, date2);
    long millisDiff = ChronoUnit.MILLIS.between(date1, date2);
    long nanoDiff = ChronoUnit.NANOS.between(date1, date2);
    
    System.out.println("Days- "+ daysDiff);
    System.out.println("Hours- "+ hoursDiff);
    System.out.println("Minutes- "+ minutesDiff);
    System.out.println("Seconds- "+ secondsDiff);
    System.out.println("Millis- "+ millisDiff);
    System.out.println("Nano Seconds- "+ nanoDiff);
  }
}
Output
Days- 1
Hours- 29
Minutes- 1752
Seconds- 105130
Millis- 105130000
Nano Seconds- 105130000000000

That's all for the topic Java Date Difference Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment