How to Calculate Date Difference in Java


In this example we will show how to calculate difference between two dates in Java.

Source Code

package com.beginner.examples;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CalculateDateDifference {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strData1 = "1999-02-02";
		String strDate2 = "2019-04-01";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
			Date date1 = sdf.parse(strData1);
			Date date2 = sdf.parse(strDate2);

			long diffTime = date2.getTime() - date1.getTime();
			System.out
					.println("The difference between two dates (milliseconds) :"
							+ diffTime);
			long diffDay = diffTime / (1000 * 60 * 60 * 24);
			System.out.println("A difference of " + diffDay + " days");

		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

Output:

The difference between two dates (milliseconds) :636163200000
A difference of 7363 days

Tips

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :

1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments