我有两个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编写的。
TimeInHours.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);