How to Get Date Difference in Java

Get Date Difference in Java

In this tutorial, I have written program about, How to Get Date Difference in Java. The same has been attached in the post.

DayDifference.java

package com.dineshkrish.date;

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class DayDifference {

	public static long getDiffernece(String strFromDate, String strToDate,
			String currentDateFormat) {

		long days = 0;

		if ((strFromDate != null && !strFromDate.isEmpty())
				&& (strToDate != null && !strToDate.isEmpty())
				&& (currentDateFormat != null && !currentDateFormat.isEmpty())) {

			try {

				DateFormat format = new SimpleDateFormat(currentDateFormat);

				Date fromDate = format.parse(strFromDate);
				Date toDate = format.parse(strToDate);

				long difference = toDate.getTime() - fromDate.getTime();

				days = difference / (24 * 60 * 60 * 1000);

			} catch (ParseException e) {

				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}

		return days;
	}

	public static void main(String[] args) {

		String strFromDate = "01/01/2016";
		String strToDate = "27/05/2016";
		String currentDateFormat = "dd/MM/yyyy";

		System.out.println("The Difference between " + strFromDate + " and "
				+ strToDate + " is "
				+ getDiffernece(strFromDate, strToDate, currentDateFormat)
				+ " Days");

	}
}

Output

The Difference between 01/01/2016 and 27/05/2016 is 147 Days

References

1. Java API Documentation
2. java.util.Date API
3. java.text.DateFormat API