Difference between two times in Android Studio, (Registered time and current time)

1.8k views Asked by At

I have a simple code, I record the time when the user hits a button and subtract that time from the current time. It should give me the difference.

The funny part is that if I print my vars they are correct but when I make the subtraction the result is the year 1969 the time the system takes as reference.

This is my code:

// I register this time to later compare to the current time.
startTime = System.currentTimeMillis().toDouble()

timer = Timer()
timer.schedule(timerTask {
    runOnUiThread {
        advanceTimer()
    }
}, 0, 60)

fun advanceTimer() {
//Total time since timer started, in seconds
val currentTime = System.currentTimeMillis().toDouble()
time = currentTime-startTime

}

This is what the console prints:

D/startTime: 2020:12:20:21:27:39:78

D/currentTime: 2020:12:20:21:29:49:21

D/time: 1969:12:31:18:02:09:42

Can somebody help me, please?

3

There are 3 answers

0
Fran On BEST ANSWER

This answer lead me the right way, actually my approach was good I just needed to make a function that showed only the difference.

I made this one. Hope it helps somebody.

Just call the function with the result of you operation, at the end I used Date().getTime() instead of System.currentTimeMillis() but I think it should be the same.

The complete code:

startTime = System.currentTimeMillis().toDouble()

timer = Timer()
timer.schedule(timerTask {
    runOnUiThread {
        advanceTimer()
    }
}, 0, 60)

fun advanceTimer() {
//Total time since timer started, in seconds
val currentTime = System.currentTimeMillis().toDouble()
time = currentTime-startTime

// Shows the time in a label on the screen
timerString.text = differenceResult(time)
}
fun differenceResult(time: Long): String {
    var x: Long = time / 1000

    var seconds = x % 60
    x /= 60
    var minutes = x % 60
    x /= 60
    var hours = (x % 24).toInt()
    x /= 24
    var days = x
    return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
0
Piyush Maheswari On
String time1 = "16:00:00";
String time2 = "19:00:00";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime(); 

This is how you calculate the time difference in Java.

0
indra lesmana On

The substraction of your date calculation is difference between two date

if you set to SimpleDateFormat date just show the difference of,

you can see at this answer https://stackoverflow.com/a/21285226/5523669