How to get the difference between two dates in java in hours/minutes ?

4.35K viewsJava
3

How to get the difference between two dates in java in hours or minutes.

For Example  :

Date startDate = “05/10/2019 09:29:58”;

Date endDate = “031/12/2019 10:31:48”;

Code return hours or minutes based on input

Anonymous Answered question June 17, 2019
Add a Comment
1

I hope the snippet code provided is sufficient for this problem, please try…!!!

public long getHrsOrMinutesDiff(Date fromDate, Date toDate, String returnType) {
		
		if ("hour".equals(returnType)) { // here if pass hours the method will return hours between the dates
			long diff = fromDate.getTime() - toDate.getTime();
			return diff / (60 * 60 * 1000);
		} else {// here if pass minutes the method will return minutes between the dates
			long diff = fromDate.getTime() - toDate.getTime();
			return diff / (60 * 1000);
		}
		
}

 

Manohar Changed status to publish June 17, 2019
Add a Comment
0
Kishore (anonymous) 0 Comments

The Below code will return days.

public long dateDifference(Date date1, Date date2) {

		long milisecond1 = date1.getTime();
		long milisecond2 = date2.getTime();
		// Find date difference in milliseconds
		long diffInMSec = milisecond2 - milisecond1;
		// Find date difference in days
		// (24 hours 60 minutes 60 seconds 1000 millisecond)
		long diffOfDays = diffInMSec / (24 * 60 * 60 * 1000);
		return diffOfDays;
}

 

Try and give the comments.

Manohar Changed status to publish June 17, 2019
Add a Comment
Write your answer.