Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Calculate Difference Between Two Time Periods
In this program, you'll learn to calculate the difference between two time periods in Kotlin.
Example: Calculate Difference Between Two Time Periods
class Time(internal var hours: Int, internal var minutes: Int, internal var seconds: Int)
fun main(args: Array<String>) {
val start = Time(12, 34, 55)
val stop = Time(8, 12, 15)
val diff: Time
diff = difference(start, stop)
print("TIME DIFFERENCE: ${start.hours}:${start.minutes}:${start.seconds} - ")
print("${stop.hours}:${stop.minutes}:${stop.seconds} ")
print("= ${diff.hours}:${diff.minutes}:${diff.seconds}")
}
fun difference(start: Time, stop: Time): Time {
val diff = 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 you run the program, the output will be:
TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40
In the above program, we've created a class named Time with three member variables: hours, minutes and seconds. As name suggests, they store hours, minutes and seconds of a given time respectively.
The Time class has a constructor that initializes the value of hours, minutes and seconds.
We've also created a static function difference that takes two Time variables as parameters, finds the difference and returns it as Time class.
Here's the equivalent Java code: Java program to calculate difference between two time periods
Did you find this article helpful?