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?
how to get months
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
i am trying to run this but the output which i am getting is wrong
And if I want difference in years then ?
Very Helpful:)
Thanks a lot! This post was for me very helpfull!
Att. marietto : )
good explanation.. you have to make small change in the 19 and 20 line .. keep going.. all the best.!
line 20 must be calender2….