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?
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)
}