How do I calculate difference in days between two dates?

In the following example we are going to calculate the differences between two dates. First, we will need to convert the date into the corresponding value in milliseconds and then do the math, so we can get the difference in days, hours, minutes, etc.

For example to get the difference in day we will need to divide the difference in milliseconds with (24 * 60 * 60 * 1000).

package org.kodejava.util;

import java.util.Calendar;

public class DateDifferenceExample {
    public static void main(String[] args) {
        // Creates two calendars instances
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Set the date for both of the calendar instance
        cal1.set(2020, Calendar.DECEMBER, 30);
        cal2.set(2021, Calendar.SEPTEMBER, 21);

        // Get the represented date in milliseconds
        long millis1 = cal1.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println("In milliseconds: " + diff + " milliseconds.");
        System.out.println("In seconds: " + diffSeconds + " seconds.");
        System.out.println("In minutes: " + diffMinutes + " minutes.");
        System.out.println("In hours: " + diffHours + " hours.");
        System.out.println("In days: " + diffDays + " days.");
    }
}

Here is the result:

In milliseconds: 22896000016 milliseconds.
In seconds: 22896000 seconds.
In minutes: 381600 minutes.
In hours: 6360 hours.
In days: 265 days.

The better way to get number of days between two dates is to use the Joda Time API. In the following example you can see how to calculate date difference using Joda Time: How do I get number of days between two dates in Joda Time?.

Wayan

3 Comments

  1. The day calculation is actually wrong if you cross a “Spring Forward” DST boundary. It will claim you’re only 123 days apart instead of 124 as you only went back 123 days and 23 hours.

    Reply
  2. I want to create an app, in that I want to show date difference between two dates I am getting all the codes from all the platforms but still unable to do it correctly as I am new in this android field. So I want a help from you that can you give the xml code of above example?

    Please.

    Reply

Leave a Reply to Wayan SaryadaCancel reply

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