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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
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:
1 2 3 4 5 6 7 8 9 10 |
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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.