Sunday, March 4, 2012

How do I calculate difference in days between two dates in Android?


In the following example we are going to calculate the differences between two dates. First, you'll need to convert the date value into its corresponding value in milliseconds and then do the math calculation so we can get the difference in days, hours, minutes, etc.
For example to get the difference in day you'll need to divide the difference in milliseconds with (24 * 60 * 60 * 1000).

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(2006, 12, 30);
        cal2.set(2007, 5, 3);

        // Get the represented date in milliseconds
        long milis1 = cal1.getTimeInMillis();
        long milis2 = cal2.getTimeInMillis();
        
        // Calculate difference in milliseconds
        long diff = milis2 - milis1;
        
        // 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.");
    }
}

Below is output....
In milliseconds: 10713600000 milliseconds.
In seconds: 10713600 seconds.
In minutes: 178560 minutes.
In hours: 2976 hours.
In days: 124 days.

1 comment:

  1. Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in near me. we want work out extra strategies in this regard, thanks for sharing.

    ReplyDelete