How to calculate date/time difference in Java

  • 16 January 2017
  • ADM

 

How to calculate date/time difference in Java - images/logos/java.jpg

 

Here is a simple example how to calculate the date and time difference in Java.

Example

When it came to date and time these are the ground rules:

  • 24 hours = 1 day
  • 60 minutes = 1 hour
  • 60 seconds = 1 minute
  • 1000 milliseconds = 1 second
package com.admfactory.date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifference {
    public static void main(String[] args) {
	System.out.println("Date Difference Example");
	System.out.println();

	String date1 = "2016/10/10 08:12:34";
	String date2 = "2016/12/02 23:22:11";

	System.out.println("Date1: " + date1);
	System.out.println("Date2: " + date2);
	System.out.println();
	SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	Date d1 = null;
	Date d2 = null;

	try {
	    d1 = format.parse(date1);
	    d2 = format.parse(date2);

	} catch (Exception e) {
	    e.printStackTrace();
	}

	String difference = getDifference(d1, d2);
	System.out.println(difference);
    }

    private static String getDifference(Date d1, Date d2) {
	String result = null;

	/** in milliseconds */
	long diff = d2.getTime() - d1.getTime();

	/** remove the milliseconds part */
	diff = diff / 1000;

	long days = diff / (24 * 60 * 60);
	long hours = diff / (60 * 60) % 24;
	long minutes = diff / 60 % 60;
	long seconds = diff % 60;

	result = days + " days, ";
	result += hours + " hours, ";
	result += minutes + " minutes, ";
	result += seconds + " seconds.";
	return result;
    }
}

To understand how it works you need to understand the difference between a/b and a%b.

a/b= return the division of tho numbers. e.g. 10/3 = 3

a%b= returns the remainder of two numbers. e.g 10%3=1

Output

Date Difference Example

Date1: 2016/10/10 08:12:34
Date2: 2016/12/02 23:22:11

53 days, 16 hours, 9 minutes, 37 seconds.

 

References