English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to calculate the time difference between two time periods in Kotlin.
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 running the program, 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 the given time hours, minutes, and seconds respectively.
There is a constructor that initializes hours, minutes, and seconds.
We also created a static function difference that accepts two time variables as parameters, finds the time difference, and returns it as a Time class.
This is the equivalent Java code:Java Program to Calculate the Difference Between Two Time Periods