Search code examples
javatimeoperation

Calculate difference between two times in Java


I have a doubt. I need to create a program in Java where for example I input 2 times = 14 25 12 and 7 50 25, and it subtracts to 6:34:47. How can I do that without using any API class from Java? I can only use Scanner and if statements. I tried something like below but obviously it doesnt work because for exemple for the seconds it does 12-25 = -13 and it should be 47.

int seconds = seconds2 - seconds1;
int minutes = minutes2 - minutes1;
int hours = hours2 - hours1;

This doesn’t work.


Solution

  • Have you heard of carryover?

    If diff value is <0, add 60 and subtract 1 from next higher value.

    From 7 50 25 to 14 25 12:
    hour = 14 - 7 = 7
    minute = 25 - 50 = -25
    second = 12 - 25 = -13

    So add 60 seconds, and subtract 1 minute:
    second = -13 + 60 = 47
    minute = -25 - 1 = -26

    So add 60 minutes, and subtract 1 hour:
    minute = -26 + 60 = 34
    hour = 7 - 1 = 6

    Result:
    hour = 6
    minute = 34
    second = 47

    6 34 47