Calculate difference between two dates in java

In this topic we will learn how to calculate difference between two dates in java in terms of Second/ Minutes / Hours / Days. By Using java class. In next section we will use Java api(JODA) to perform the same activity.

package com.jbt;

import java.util.Calendar;

/*
 * Here we will learn to calculate the difference in days between two date.
 * There is Java API(JODA Api) available which can also be used to calculate difference between date.
 * But here we will talk about the option available in Java only.
 */
public class CalculateDifferenceInDays {

	public static void main(String args[]) {

		// Create Calendar instance
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();

		// Set the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
		calendar1.set(2012, 2, 12);
		calendar1.set(2011, 3, 12);

		/*
		 * Use getTimeInMillis() method to get the Calendar's time value in
		 * milliseconds. This method returns the current time as UTC
		 * milliseconds from the epoch
		 */
		long miliSecondForDate1 = calendar1.getTimeInMillis();
		long miliSecondForDate2 = calendar2.getTimeInMillis();

		// Calculate the difference in millisecond between two dates
		long diffInMilis = miliSecondForDate2 - miliSecondForDate1;

		/*
		 * Now we have difference between two date in form of millsecond we can
		 * easily convert it Minute / Hour / Days by dividing the difference
		 * with appropriate value. 1 Second : 1000 milisecond 1 Hour : 60 * 1000
		 * millisecond 1 Day : 24 * 60 * 1000 milisecond
		 */

		long diffInSecond = diffInMilis / 1000;
		long diffInMinute = diffInMilis / (60 * 1000);
		long diffInHour = diffInMilis / (60 * 60 * 1000);
		long diffInDays = diffInMilis / (24 * 60 * 60 * 1000);

		System.out.println("Difference in Seconds : " + diffInSecond);
		System.out.println("Difference in Minute : " + diffInMinute);
		System.out.println("Difference in Hours : " + diffInHour);
		System.out.println("Difference in Days : " + diffInDays);

	}

}

Output of the above code would be

Difference in Seconds : 45100800
Difference in Minute : 751680
Difference in Hours : 12528
Difference in Days : 522

 

What about the days that have 23 or 25 hours due to a DST transition?

Reference

8 Comments Calculate difference between two dates in java

  1. Nick

    these 2 calculations give incorrect results:

    01/15/08 to 03/15/10: The correct answer is 790. The program produces 789.

    12/30/13 to 02/28/17: The correct answer is 1156. The program produces 1152

    Is it the code or the Calendar class?
    Thanks

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.