首页 > 解决方案 > 如何在 android 中将 2021-07-06T19:27:46.811+0530 格式转换为 d MMM yyyy, hh:mm aaa 这种格式

问题描述

2021-07-06T19:27:46.811+0530 -> 当前值作为字符串

我想转换为 05/07/2021, 06:45 am 这种格式

提前致谢

标签: androiddatetimekotlinsimpledateformat

解决方案


使用java.time

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

fun main() {
    val input = "2021-07-06T19:27:46.811+0530"
    // define a DateTimeFormatter for parsing your input
    val parser = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSx")
    // and another one for formatting your output
    val formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu, hh:mm a")
    // then parse the input to an OffsetDateTime using the parser
    val converted: String = OffsetDateTime.parse(input, parser)
                                          // and output the same time differently
                                          .format(formatter)
    // output the result
    println(converted)
}

此代码的输出是

06/07/2021, 07:27 PM

好的,这与显示您所需输出的示例的值不完全一样,但我认为这与此处的格式有关。调整这些值需要更多的努力,包括对所需行为的简要描述。


推荐阅读