English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program to calculate the time difference between two time periods

Comprehensive Java Examples

In this program, you will learn how to calculate the time difference between two time periods in Java.

Example: Calculate the time difference between two time periods

public class Time {
    int seconds;
    int minutes;
    int hours;
    public Time(int hours, int minutes, int seconds) {
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
    }
    public static void main(String[] args) {
        Time start = new Time(12, 34, 55),
                stop = new Time(8, 12, 15),
                diff;
        diff = difference(start, stop);
        System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds);
        System.out.printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds);
        System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);
    }
    public static Time difference(Time start, Time stop)
    {
        Time diff = new Time(0, 0, 0);
        if(stop.seconds > start.seconds){
            --start.minutes;
            start.seconds += 60;
        }
        diff.seconds = start.seconds - stop.seconds;
        if(stop.minutes > start.minutes){
            --start.hours;
            start.minutes += 60;
        }
        diff.minutes = start.minutes - stop.minutes;
        diff.hours = start.hours - stop.hours;
        return(diff);
    }
}

When the program is run, the output is:

TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40

In the above program, we have created a class named Time with three member variables hours, minutes, and seconds. As the name suggests, they store hours, minutes, and seconds of the given time respectively.

The Time class has a constructor that initializes hours, minutes, and seconds.

We have also created a static function difference that accepts two time variables as parameters, finds the difference, and returns it as a Time class

Comprehensive Java Examples