原文: https://www.programiz.com/kotlin-programming/examples/difference-time
在此程序中,您将学习计算 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
}
运行该程序时,输出为:
TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40
在上述程序中,我们创建了一个名为Time
的类,该类具有三个成员变量:hour
,minutes
和seconds
。 顾名思义,它们分别存储给定时间的hour
,minutes
和seconds
。
Time
类具有一个构造器,该构造器初始化hour
,minutes
和seconds
的值。
我们还创建了一个静态函数差异,该差异将两个Time
变量作为参数,找到该差异并将其作为Time
类返回。
以下是等效的 Java 代码:用于计算两个时间段之间的差异的 Java 程序