0

I have a clock in and clock out time stored in my program in the format HH/MM/SS as a string. How can I calculate the difference in hours, minutes and seconds between the two? I can convert the two to back to dates if necessary but cannot for the life of me figure out how to calculate the difference!

e.g.

clockIn = 12:10:45 clockout = 14:10:50

timeDiff should be 02:00:15.

Thanks in advance.

2 Answers2

2

Once you have the two dates, you can all getTime() to get the time in milliseconds:

long date1Ms = clockIn.getTime();
long date2Ms = clockOut.getTime();
long difference = date1Ms - date2Ms;

Once you have the difference in Ms, converting to Hours/Minutes/Seconds is easy:

    int hoursDiff = (int) (difference / (60 * 60 * 1000));
    int hoursMs = hoursDiff * 60 * 60 * 1000;
    int minsDiff = (int) ((difference - hoursMs) / (60 * 1000));
    int minsMs = hoursMs + minsDiff * 60 * 1000;
    int secDiff = (int) ((difference - minsMs) / 1000);

Here, hoursDiff, minsDiff and secDiff gives you the segments you needed.

pRaNaY
  • 24,642
  • 24
  • 96
  • 146
Adrian Pang
  • 1,125
  • 6
  • 12
0

You can do something like this to achieve the time difference

SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");

Date d1 = sdf.parse("12:10:45");
Date d2 = sdf.parse("14:10:50");

long diff = Math.abs(d1.getTime() - d2.getTime());
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;

System.out.println(diffHours+":"+diffMinutes+":"+diffSeconds);

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33