Kotlin 从日期中提取时间

问题描述 投票:0回答:2

我有一个采用该格式的日期:2027-02-14T14:20:00.000

我想从中花费几小时和几分钟,就像在这种情况下:14:20

我正在尝试做这样的事情:

val firstDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2027-02-14T14:20:00.000")
val firstTime = SimpleDateFormat("H:mm").format(firstDate)

但是我崩溃了

java.text.ParseException: Unparseable date

如何从该字符串中获取小时和分钟?

android kotlin date datetime simpledateformat
2个回答
5
投票

推荐的方法之一

如果您可以使用

java.time
,这里有一个带注释的示例:

import java.time.LocalDateTime
import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun main() {
    // example String
    val input = "2027-02-14T14:20:00.000"
    // directly parse it to a LocalDateTime
    val localDateTime = LocalDateTime.parse(input)
    // print the (intermediate!) result
    println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
    // then extract the date part
    val localDate = localDateTime.toLocalDate()
    // print that
    println(localDate)
}

这会输出 2 个值,解析的中间

LocalDateTime
和提取的
LocalDate
(后者只是隐式调用其
toString()
方法):

2027-02-14T14:20:00
2027-02-14

不推荐,但仍然可能:

仍然使用过时的 API(当涉及大量遗留代码时可能是必要的,我怀疑你会发现这些代码是用 Kotlin 编写的):

import java.text.SimpleDateFormat

fun main() {
    val firstDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
                               .parse("2027-02-14T14:20:00.000")
    val firstTime = SimpleDateFormat("yyyy-MM-dd").format(firstDate)
    println(firstTime)
}

输出:

2027-02-14

0
投票

您可以使用这个:

val date = SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(Date())
© www.soinside.com 2019 - 2024. All rights reserved.