【问题标题】:How to find difference between two UNIX time stamp in hours in KOTLIN?如何在 KOTLIN 中以小时为单位查找两个 UNIX 时间戳之间的差异?
【发布时间】:2018-08-21 13:38:05
【问题描述】:

我有两个 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 分钟。

【问题讨论】:

标签: android datetime unix kotlin unix-timestamp


【解决方案1】:

这是我的解决方案,代码是用 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

【讨论】:

    【解决方案2】:

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

        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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 2021-01-12
      • 2021-05-14
      • 1970-01-01
      • 2020-06-08
      相关资源
      最近更新 更多