如何在 KOTLIN中以小时为单位找到两个UNIX时间戳之间的差异?



我有两个 UNIX 时间戳,我正在使用 KOTLIN

1( 旧时光 - 1534854646 2( 当前时间 - 1534857527

现在我想要小时和分钟的差异。

val result = DateUtils.getRelativeTimeSpanString(1534854646, 1534857527, 0)

但它给了我 2 秒,但实际时差约为 0 小时 48 分钟。

我也试过:

long mills = 1534857527 - 1534854646;
int hours = millis/(1000 * 60 * 60);
int mins = (mills/(1000*60)) % 60;
String diff = hours + ":" + mins; 

但它仍然给出 0 小时 0 分钟。

这是我的解决方案,代码是用 Kotlin 编写的。

时间在小时.kt

class TimeInHours(val hours: Int, val minutes: Int, val seconds: Int) {
override fun toString(): String {
return String.format("%dh : %02dm : %02ds", hours, minutes, seconds)
}
}

编写一个函数,将持续时间(以秒为单位(转换为TimeInHours

fun convertFromDuration(timeInSeconds: Long): TimeInHours {
var time = timeInSeconds
val hours = time / 3600
time %= 3600
val minutes = time / 60
time %= 60
val seconds = time
return TimeInHours(hours.toInt(), minutes.toInt(), seconds.toInt())
}

Test.kt

val oldTime: Long = 1534854646
val currentTime: Long = 1534857527
val result = convertFromDuration(currentTime - oldTime)
Log.i("TAG", result.toString())

输出:

I/TAG: 0h : 48m : 01s

做这样的事情,我还没有测试过这个,但它应该可以工作

long mills = 1534857527 - 1534854646;
String period = String.format("%02d:%02d", 
TimeUnit.MILLISECONDS.toHours(mills),
TimeUnit.MILLISECONDS.toMinutes(mills) % TimeUnit.HOURS.toMinutes(1));
System.out.println("Duration hh:mm -  " + period);

基于孙长上面的正确答案,我在课堂内添加了乐趣,将所有内容都放在同一个班级中,并增加了几天的支持:

class TimeInHours(val days: Int, val hours: Int, val minutes: Int, val seconds: Int) {
companion object {
fun convertFromDuration(timeInSeconds: Long): TimeInHours {
var time = timeInSeconds
val days = time / 86400
time %= 86400
val hours = time / 3600
time %= 3600
val minutes = time / 60
time %= 60
val seconds = time
return TimeInHours(days.toInt(), hours.toInt(), minutes.toInt(), seconds.toInt())
}
}
override fun toString(): String {
return String.format("%dd : %dh : %02dm : %02ds", days, hours, minutes, seconds)
}

}

用法:

val currentTime: Long = System.currentTimeMillis() / 1000
val oldTime: Long = 1682613120
val result = TimeInHours.convertFromDuration(currentTime - oldTime)
print("Result: "+ result.toString())

输出:

Result: 7d : 3h : 16m : 28s

最新更新