1

Here I have got the code part which counts the difference between two times(time1,time2). How can I add seconds to it and convert 60sec to one minute?

I assume there is a simpler way to deal with it, but I am studying with book for beginners so I'd like to get the answer in the same way as the hours and minutes are calculated here.

  hours=time2/100-time1/100;
  mins=time2%100-time1%100;

  hours=mins>0?hours:hours-1;
  mins=mins>0?mins:mins+60;
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

0
 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        long startTime = sdf.parse("10:00:00").getTime();
        long endTIme = sdf.parse("11:00:00").getTime();
        long duration = endTIme - startTime;

        int seconds = (int) (duration / 1000) % 60;
        int minutes = (int) ((duration / (1000 * 60)) % 60);
        int hours = (int) ((duration / (1000 * 60 * 60)) % 24);
gjman2
  • 912
  • 17
  • 28
0

I am assume you have implemented the time as a number like 1234 is 12:34 In this case it is easier to parse each time and compare.

int mins1 = time1 / 100 * 60 + time1 % 100;
int mins2 = time2 / 100 * 60 + time2 % 100;
int diff = mins2 - mins1;

i want to do is input number 123456 which would be equal to 12:34:56

To handle seconds, you can do.

int secs1 = time1 / 10000 * 60 * 60 + time1 /100 % 100 * 60 + time1 % 100;
int secs2 = time2 / 10000 * 60 * 60 + time2 /100 % 100 * 60 + time2 % 100;
int diffInSec = secs1 - secs2;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • @Anders R. Bystrup Input number is like 1234, not 12:34, and what i want to do is input number 123456 which would be equal to 12:34:56, then find the difference – user2745860 Sep 04 '13 at 13:07