- · First, create a class “Time” with three member variables hours, minutes and seconds.
- · Initialize the constructor
- · Create a function “Difference” and initialise the time values as zero.
- · If seconds values(stop) are greater than minutes are converted into seconds . In the same way, minutes(stop) are greater than hour, convert the hour value to minutes.
- · Now, find the difference between hours, minutes and seconds.
- · Create the public static void main(). There, Assign the values for starting and stopping time.
- · Call the difference function to find the difference between two time.
- · Print the output by print() function.
//Java Program to calculate Time difference.
class Time {
int hours;
int minutes;
int seconds;
public Time(int
hours, int minutes, int seconds) {
this.hours =
hours;
this.minutes =
minutes;
this.seconds =
seconds;
}
public static Time
difference(Time starting, Time stopping) {
Time diff =
new Time(0, 0, 0);
// If start
second is greater than stop second, convert minute of stop into seconds
if (starting.seconds
> stopping.seconds) {
--stopping.minutes;
stopping.seconds
+= 60;
}
diff.seconds =
stopping.seconds - starting.seconds;
// If start
minute is greater is than stop minute, convert stop hour into minutes
if (starting.minutes
> stopping.minutes) {
--stopping.hours;
stopping.minutes
+= 60;
}
// Find the difference by subtracting stop and start value.
diff.minutes =
stopping.minutes - starting.minutes;
diff.hours =
stopping.hours - starting.hours;
return diff;
}
public void print()
{
System.out.printf("%d:%d:%d\n", hours, minutes, seconds);
}
public static void
main(String[] args) {
Time start =
new Time(5, 42, 15);
Time stop =
new Time(11, 34, 55);
Time diff =
Time.difference(start, stop);
System.out.print("Time Difference: ");
diff.print();
}
}
- Open the command prompt. Set the path and compile the program.
- If there is no error, execute the program.
- It displays the time difference between two times.
Thus the way of of creating a java program to find the time difference.
No comments:
Post a Comment