I have the following Kotlin code for simple countdown timer:
val thousand: Long = 1000
val timer = object: CountDownTimer(1800000, 1000) {
override fun onTick(millisUntilFinished: Long) {
var timeResult = millisUntilFinished/thousand
textTimer.text = "$timeResult"
}
override fun onFinish() {
textTimer.text = "Time is out"
}
}
timer.start()
textTimer.text = "$timer"
How to format 1800 seconds to 30 min : 00 sec in Kotlin?
You get the numbers by integer division and modulo (%)
and the formatting to 2 digits with padStart():
val secs = 1800
val formatted = "${(secs / 60).toString().padStart(2, '0')} min : ${(secs % 60).toString().padStart(2, '0')} sec"
println(formatted)
will print
30 min : 00 sec
Since you are targeting the JVM, you should use the Java 8 Date/Time Api. You could create a very concise function like this:
fun countdown(s: Long) = with(LocalTime.ofSecondOfDay(s)) {
String.format("%02d min :%02d sec", minute, second)
}
countdown(1800) // 30 min : 00 sec
Recommendation:
Don't do the calculations at call site (in onTick). This makes the code unecessary hard to understand. Create a separate function for that.
It's a simple calculation, but use what the standard libraries give you. Firstly, the code is optimized and secondly you can easily extend the function to calculate hours and so on. Untested, hand-drafted code is error prone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With