-1

I have two UNIX time stamp and i am using KOTLIN

1) old time - 1534854646 2) current time - 1534857527

Now i want the difference in hours and minutes.

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

But it gives me 2 seconds but actual time difference is around 0 hour and 48 minutes.

I have also tried :

long mills = 1534857527 - 1534854646;
int hours = millis/(1000 * 60 * 60);
int mins = (mills/(1000*60)) % 60;

String diff = hours + ":" + mins; 

But still it gives 0 hours and 0 minute.

2 Answers2

3

Here is my solution, the code is written in 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)
        }
}

Write a function which converts time duration in seconds to 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())

Output:

I/TAG: 0h : 48m : 01s
Son Truong
  • 12,343
  • 5
  • 28
  • 54
1

Do something like this, I have not tested this but it should work

    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);
Qasim
  • 5,061
  • 4
  • 29
  • 49