Duration or difference between two dates

Java examples to calculate the duration or difference between two date instances (Date and LocalDate classes).

Duration between two LocalDate instances

Use Duration.between() method to get the difference between two local date instances.

//First LocalDate
LocalDate today = LocalDate.now();		//1

//Second LocalDate
LocalDate sameDayNextMonth = LocalDate.now().plusMonths(1);		//2

//Difference between dates
Duration duration = Duration.between( today.atStartOfDay(), 
				sameDayNextMonth.atStartOfDay() );

//Verify differences
duration.toDays();			//31
duration.toHours();			//744
duration.toMinutes();		//44640
duration.toSeconds();		//2678400
duration.toMillis();		//2678400000

Difference between two Date instances

Use Duration.between() method to get the difference between two date instances.

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main 
	public static void main(String[] args) 
		//First Date
		Date today = new Date();
		//Second Date
		Date sameDayNextMonth = new Date();
		sameDayNextMonth.setMonth(today.getMonth() + 1);
		long days = getDateDiff (today, sameDayNextMonth, TimeUnit.DAYS);			//31
		long hours = getDateDiff (today, sameDayNextMonth, TimeUnit.HOURS);			//744
		long minutes = getDateDiff (today, sameDayNextMonth, TimeUnit.MINUTES);		//44640
		long seconds = getDateDiff (today, sameDayNextMonth, TimeUnit.SECONDS);		//2678400
		long mills = getDateDiff (today, sameDayNextMonth, TimeUnit.MILLISECONDS);	//2678400000
	public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) 
	    long diffInMillies = date2.getTime() - date1.getTime();
	    return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);

Happy Learning !!

  1. Duration Javadoc
  2. LocalDate Javadoc
  3. Date Javadoc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Duration or difference between two dates”

  1. Hello Sir,

    In case of minutes we are passing TimeUnit.MINUTES, but this function :
    getDateDiff(Date date1, Date date2, TimeUnit timeUnit) passes TimeUnit.MILLISECONDS as second argument in convert method.

    Please could you explain it a bit about it more. How is this working in this case?

    Thanks in advance,


Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.