ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Kotlin 程序:计算两个时间段之间的差异 > 原文: [https://www.programiz.com/kotlin-programming/examples/difference-time](https://www.programiz.com/kotlin-programming/examples/difference-time) #### 在此程序中,您将学习计算 Kotlin 中两个时间段之间的时差。 ## 示例:计算两个时间段之间的差异 ```kt 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 } ``` 运行该程序时,输出为: ```kt 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 程序](/java-programming/examples/difference-time "Java program to calculate difference between two time periods")