在Kotlin中解析持续时间字符串 [英] Parsing a Duration String in Kotlin

查看:191
本文介绍了在Kotlin中解析持续时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android应用程序,并且需要解析格式为"00:00:00.000"(例如:"00:00:38.47"或"00:03:27.11")的持续时间字符串. /p>

我的最终目标是将该字符串转换为毫秒总数的两倍,以获取进度百分比.

我已经研究过SimpleDateFormatter,但是在理解它的工作方式或应该如何使用它方面遇到了一些问题.

我已经尝试过了:

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

那么有没有一种简单/有效的方法来做到这一点?

解决方案

  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)

输出:

68
68830000000
68.83

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 ?

解决方案

  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

这篇关于在Kotlin中解析持续时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆