Kotlin:将日期字符串转换为 ISO 字符串

waw*_*los 2 java date kotlin

我有一个具有以下格式的日期字符串:MM/DD/2019 可能的值可以是1/16/201911/31/2019例如。

我正在寻找一种方法来转换这个字符串值以获得以下格式:

2019-11-31 15:07:57.013Z
Run Code Online (Sandbox Code Playgroud)

我怎么能在 Kotlin 中做到这一点?

rva*_*lez 5

Kotlin 的一大优点是您可以重用 Java 库,因此 java.time可以像这样使用库:

import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter

class ApplicationTests {
    @Test
    fun changeDateFormat(){
        val inputDateString = "11/31/2019"
        val inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")
        val localDate = LocalDate.parse(inputDateString, inputFormatter)
        val outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ")
        val localDateTime = localDate.atStartOfDay()
        val zonedDateTime = localDateTime.atZone(ZoneId.of("America/New_York"))
        val outputDateString = outputFormatter.format(zonedDateTime)
        print(outputDateString)
    }
}
Run Code Online (Sandbox Code Playgroud)

运行该测试将打印2019-12-01 00:00:00.000-0500为输出。

新格式有小时和分钟,因此LocalDate需要将其转换为LocalDateTime,并且可以通过atStartOfDay(),作为一个选项来完成atTime(H,M)

新格式还有一个时区,因此您需要将其转换为 可用于该时区ZonedDateTime 的方法.atZone(..)


java.text.SimpleDateFormat 也可以在几行中使用:

val date = SimpleDateFormat("MM/dd/yyyy").parse("11/31/2019")
print(SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ").format(date))
Run Code Online (Sandbox Code Playgroud)

但作为@OleV.V. 指出它已经过时并且有一些麻烦(比如不考虑时间和时区可能会导致不希望的错误)。


小智 5

ISO格式转换请参考此:https://mincong-h.github.io/2017/02/16/convert-date-to-string-in-java/

    String dateStr = "1/16/2019";

    Date date = new SimpleDateFormat("MM/dd/yyyy").parse(dateStr);

    SimpleDateFormat sdf;
    sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    sdf.setTimeZone(TimeZone.getTimeZone("CET"));
    String dateText = sdf.format(date);

    System.out.println(dateText);
Run Code Online (Sandbox Code Playgroud)

  • 这些约会时间课程太糟糕了。它们在几年前就被 JSR 310 中定义的现代 *java.time* 类所取代。 (3认同)