How to calculate the difference between two time periods in Java

2 Answers

0 votes
public class TimeDiff {
    int seconds;
    int minutes;
    int hours;

    public TimeDiff(int hours, int minutes, int seconds) {
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
    }
    
    public static TimeDiff timeDifference(TimeDiff start, TimeDiff end) {
        TimeDiff timediff = new TimeDiff(0, 0, 0);

        if (start.seconds > end.seconds) {
            end.minutes--;
            end.seconds += 60;
        }

        timediff.seconds = end.seconds - start.seconds;

        if (start.minutes > end.minutes ) {
            end.hours--;
            end.minutes += 60;
        }

        timediff.minutes = end.minutes - start.minutes;
        timediff.hours = end.hours - start.hours;

        return timediff;
    }
    
    public static void main(String args[]) {
        TimeDiff start = new TimeDiff(7, 11, 13);
        TimeDiff end = new TimeDiff(10, 46, 27);

        TimeDiff timediff = timeDifference(start, end);

        System.out.printf("%d:%d:%d - ", start.hours, start.minutes, start.seconds);
        System.out.printf("%d:%d:%d ", end.hours, end.minutes, end.seconds);
        System.out.printf("= %d:%d:%d\n", timediff.hours, timediff.minutes, timediff.seconds);
    }
}




/*
run:

7:11:13 - 10:46:27 = 3:35:14

*/

 



answered Jan 14, 2022 by avibootz
0 votes
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDiff {
    public static void main(String args[]) throws Exception {
        String time1 = "7:11:13";
        String time2 = "10:46:27";
  
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
  
        Date date1 = simpleDateFormat.parse(time1);
        Date date2 = simpleDateFormat.parse(time2);
  
        long diffInMilliSeconds = Math.abs(date2.getTime() - date1.getTime());
  
        long diffInHours = (diffInMilliSeconds / (60 * 60 * 1000)) % 24;
  
        long diffInMinutes = (diffInMilliSeconds / (60 * 1000)) % 60;
  
        long diffInSeconds = (diffInMilliSeconds / 1000) % 60;
  
        System.out.println(diffInHours + ":" + diffInMinutes + ":" + diffInSeconds);
    }
}




/*
run:

3:35:14

*/

 



answered Jan 14, 2022 by avibootz

Related questions

1 answer 163 views
1 answer 152 views
1 answer 160 views
1 answer 172 views
1 answer 155 views
...