How to calculate difference between two dates in java

In this post, we will see how to calculate difference between two dates. Sometimes we have requirement to find no. of days between two dates or no. of hours between two dates.

Java Program:
package com.org.arpit.java2blog;
 
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * @author java2blog.com
 * Arpit Mandliya
 * 
 */ 
public class DateDiff {
 
    public static void main(String[] args) {
        try {
            String date1 = "04/21/2016";
            String date2 = "04/24/2016";
     
            String format = "MM/dd/yyyy";
 
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date dateObj1 = sdf.parse(date1);
            Date dateObj2 = sdf.parse(date2);
            
            System.out.println("Date 1:"+dateObj1);
            System.out.println("Date 2:"+dateObj2 + "\n");
 
            // For thousand separator
            DecimalFormat decimalFormatter = new DecimalFormat("###,###");
 
            long diffInMilliSeconds = dateObj2.getTime() - dateObj1.getTime();
 
            System.out.println("difference in milliseconds: " + decimalFormatter.format(diffInMilliSeconds));
            
            int diffsec = (int) (diffInMilliSeconds / (1000));
            System.out.println("difference in seconds: " + decimalFormatter.format(diffsec));
            
            int diffInMin = (int) (diffInMilliSeconds / (60 * 1000));
            System.out.println("difference in minutes: " + decimalFormatter.format(diffInMin));
            
            int diffInHours = (int) (diffInMilliSeconds / (60 * 60 * 1000));
            System.out.println("difference in hours: " + decimalFormatter.format(diffInHours));
            
            int diffInDays = (int) (diffInMilliSeconds / (24 * 60 * 60 * 1000));
            System.out.println("difference in days: " + diffInDays);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
When you run above program, you will get following output:
Date 1:Thu Apr 21 00:00:00 IST 2016
Date 2:Sun Apr 24 00:00:00 IST 2016

difference in milliseconds: 259,200,000
difference between seconds: 259,200
difference in minutes: 4,320
difference in hours: 72
difference in days: 3

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012