Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a Duration String in Kotlin

I'm working on a Android application and I need to parse a duration string of this form "00:00:00.000" (Ex: "00:00:38.47" or "00:03:27.11").

My final goal is to convert this string into a double of total seconds with milliseconds to get a progression percent.

I already looked into SimpleDateFormatter, but I'm having some issue understanding how it works or how I'm supposed to use it.

I've tried this:

val timeString = "00:01:08.83"
val df = SimpleDateFormat("HH:mm:ss.SS")
df.parse(timeString)?.seconds!!.toFloat() // Returns 8.00, I want to have 68.83 for this example string

So is there a simple/efficient way of doing this ?

like image 235
NhgrtPlayer Avatar asked Nov 02 '19 12:11

NhgrtPlayer


1 Answers

  val time = LocalTime.parse("00:01:08.83", DateTimeFormatter.ofPattern("HH:mm:ss.SS"))

  println(time.toSecondOfDay())
  println(time.toNanoOfDay())
  println(time.toNanoOfDay().toFloat() / 1_000_000_000)

Output:

68
68830000000
68.83
like image 58
Lachezar Balev Avatar answered Sep 26 '22 01:09

Lachezar Balev