How to get day difference between two dates in java

This example show you how you can get the difference between two java dates, first we have to get the time of dates in milliseconds and get the difference in seconds, minutes, hours and days.

package com.java.connect.date;
 
import java.util.Calendar;
 
public class DayDifferenceBetweenTwoDatesExample {
    public static void main(String[] args) {
        // Create two calendars instances
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        // Set the date for both of the calendar instance
        calendar1.set(2010, 5, 25);
        calendar2.set(2011, 5, 6);
        // Get the represented date in milliseconds
        long milisecond1 = calendar1.getTimeInMillis();
        long milisecond2 = calendar2.getTimeInMillis();
        // Calculate difference in milliseconds
        long difference = milisecond2 - milisecond1;
        // Calculate difference in seconds
        long differenceInSeconds = difference / 1000;
        // Calculate difference in minutes
        long differenceInMinutes = difference / (60 * 1000);
        // Calculate difference in hours
        long differenceInHours = difference / (60 * 60 * 1000);
        // Calculate difference in days
        long differenceInDays = difference / (24 * 60 * 60 * 1000);
        System.out.println("Difference in milliseconds: " + difference + " milliseconds.");
        System.out.println("Difference in seconds: " + differenceInSeconds + " seconds.");
        System.out.println("Difference in minutes: " + differenceInMinutes + " minutes.");
        System.out.println("Difference in hours: " + differenceInHours + " hours.");
        System.out.println("Difference in days: " + differenceInDays + " days.");
    }
}

The output of above example will be as:

Difference in milliseconds: 29894400000 milliseconds.
Difference in seconds: 29894400 seconds.
Difference in minutes: 498240 minutes.
Difference in hours: 8304 hours.
Difference in days: 346 days.