Java difference between two dates in years.

Java difference between two dates in years.


Posted in : Core Java Posted on : November 29, 2010 at 3:53 PM Comments : [ 0 ]

Java difference between two dates in years.

Java difference between two dates in years

In this example, you will see how to calculate years in between to date.

Code:

DiffeYear.java
import java.util.Calendar;

public class DiffeYear {
	public static void main(String[] arr) {
		Calendar firstCal = Calendar.getInstance();
		// set first date
		firstCal.set(2010, 10, 25);
		Calendar secondCal = Calendar.getInstance();
		// set second date
		secondCal.set(1986, 10, 25);
		// Convert date into millisecond
		long firstMilliSecond = firstCal.getTimeInMillis();
		long secondMilliSecond = secondCal.getTimeInMillis();
		// Calculate difference in millisecond
		long differMilliSecond = firstMilliSecond - secondMilliSecond;
		// Convert millisecond into second
		long differSecond = differMilliSecond / 1000;
		// Convert second into minutes
		long differMinutes = differSecond / 60;
		// Convert minutes into hours
		long differHours = differMinutes / 60;
		// Convert hours into days
		long differDays = differHours / 24;
		// Convert days into month
		long differMonth = differDays / 30;
		// Convert month into year
		long differYear = differMonth / 12;
		System.out.println("Total number of year between two date :  "
				+ differYear);
	}
}

Output

Total number of year between two date : 24

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics