In this post we’ll see how to calculate date-time difference between two dates in Java using the new date and time API in Java 8 -
Using Java 8 Period and Duration classes
If you are using Java 8 then you can use new data and time API classes Period and Duration.
Here Period class models amount of time in terms of years, months and days and Duration class models amount of time in terms of seconds and nanoseconds.
Java code
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
public class DateDiff {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(2016, 8, 28, 13, 15, 55);
LocalDateTime dateTime2 = LocalDateTime.of(2016, 8, 29, 17, 18, 14);
getPeriod(dateTime1.toLocalDate(), dateTime2.toLocalDate());
getTime(dateTime1.toLocalTime(), dateTime2.toLocalTime());
}
/**
*
* @param date1
* @param date2
*/
private static void getPeriod(LocalDate date1, LocalDate date2){
Period p = Period.between(date1, date2);
System.out.println("Year " + p.getYears());
System.out.println("Months " + p.getMonths());
System.out.println("Days " + p.getDays());
}
/**
*
* @param time1
* @param time2
*/
private static void getTime(LocalTime time1, LocalTime time2){
Duration d = Duration.between(time1, time2);
long seconds = d.getSeconds();
//System.out.println("seconds " + seconds);
// Calculating hours
System.out.println("Hours " + d.toHours());
// Calculating Minutes
System.out.println("Minutes " + ((seconds % 3600)/60));
// Calculating Seconds
System.out.println("Seconds " + (seconds % 60));
}
}
Output
Year 0
Months 0
Days 1
Hours 4
Minutes 2
Seconds 19
Running it with another set of dates -
LocalDateTime dateTime1 = LocalDateTime.of(2016, 8, 28, 13, 15, 55);
LocalDateTime dateTime2 = LocalDateTime.of(2017, 10, 5, 15, 12, 59);
Output
Year 1
Months 1
Days 7
Hours 1
Minutes 57
Seconds 4
That's all for this topic Difference Between Two Dates - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -