Skip to content

Instantly share code, notes, and snippets.

@git-santosh
Last active July 11, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save git-santosh/f982bc03b148fd77b1c56c4adb204931 to your computer and use it in GitHub Desktop.
Save git-santosh/f982bc03b148fd77b1c56c4adb204931 to your computer and use it in GitHub Desktop.
How to calculate date and time difference in Java
pre[class*=language-] {
padding: 1rem 0 1rem 1rem!important;
margin-top: 0;
margin-bottom: 1rem;
border: 1px solid #d1d1e8;
background-color: #f7f7f9;
}
@git-santosh
Copy link
Author

git-santosh commented Jul 11, 2019

1. Manual time calculation

Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :

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

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

public class DateDifferentExample {

public static void main(String[] args) {

	String dateStart = "01/14/2012 09:29:58";
	String dateStop = "01/15/2012 10:31:48";

	//HH converts hour in 24 hours format (0-23), day calculation
	SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

	Date d1 = null;
	Date d2 = null;

	try {
		d1 = format.parse(dateStart);
		d2 = format.parse(dateStop);

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

		long diffSeconds = diff / 1000 % 60;
		long diffMinutes = diff / (60 * 1000) % 60;
		long diffHours = diff / (60 * 60 * 1000) % 24;
		long diffDays = diff / (24 * 60 * 60 * 1000);

		System.out.print(diffDays + " days, ");
		System.out.print(diffHours + " hours, ");
		System.out.print(diffMinutes + " minutes, ");
		System.out.print(diffSeconds + " seconds.");

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

}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment