Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two times in minutes [closed]

Tags:

java

time

I've seen some examples using Joda Time and other methods to work out the difference between two dates in milliseconds, but how can these be applied to just get the difference between two times in minutes? For example, the difference between 2:45pm and 11:00am is 225 minutes.

like image 307
user2704743 Avatar asked Dec 02 '22 21:12

user2704743


1 Answers

You can work out the math by observing that one minute is sixty seconds, one second is one thousand milliseconds, so one minute is 60*1000 milliseconds.

If you divide milliseconds by 60,000, seconds will be truncated. You should divide the number by 1000 to truncate milliseconds, then take n % 60 as the number of seconds and n / 60 as the number of minutes:

Date d1 = ...
Date d2 = ...
long diffMs = d1.getTime() - d2.getTime();
long diffSec = diffMs / 1000;
long min = diffSec / 60;
long sec = diffSec % 60;
System.out.println("The difference is "+min+" minutes and "+sec+" seconds.");
like image 157
Sergey Kalinichenko Avatar answered Dec 18 '22 06:12

Sergey Kalinichenko