如何在 Scala 中将格式为“2024-08-19 00:20:04.0 +2:00”的字符串转换为日期时间格式

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

我有字符串,我想转换为具有相同格式的 toLocalDateTime 。但是当我尝试相同的格式“yyyy-MM-dd HH:mm:ss.S Z”时,它无法转换,因为它没有解析时区偏移量:

LocalDateTime.parse("2024-08-19 00:20:04.0 +2:00",java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S Z"))

它给出以下错误:

 LocalDateTime.parse("2024-08-19 00:20:04.0 +2:00",java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S Z"))
java.time.format.DateTimeParseException: Text '2024-08-19 00:20:04.0 +2:00' could not be parsed at index 22
  at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2056)
  at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1958)
  at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:494)
  ... 30 elided

我尝试用 z 替换 Z 但同样的问题,我也尝试用仍然相同的错误替换 Z 有一种方法可以将包含时区偏移的字符串(如“+2:00”)转换为以下格式的日期时间: “2024-08-19 00:20:04.0 +2:00”

java scala datetime
2个回答
3
投票

您需要一个具有自定义格式的

DateTimeFormatter
,如下例所示:

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                    .append(DateTimeFormatter.ISO_DATE)
                    .appendLiteral(' ')
                    .append(DateTimeFormatter.ISO_LOCAL_TIME)
                    .appendLiteral(' ')
                    .appendOffset("+H:mm", "")
                    .toFormatter(Locale.ENGLISH);
        

使用它将日期时间字符串解析为

OffsetDateTime
,从中您可以获得
LocalDateTime

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .appendLiteral(' ')
                .appendOffset("+H:mm", "")
                .toFormatter(Locale.ENGLISH);

        OffsetDateTime odt = OffsetDateTime.parse("2024-08-19 00:20:04.0 +2:00", dtf);
        LocalDateTime ldt = odt.toLocalDateTime();
        System.out.println(ldt);
    }
}

输出:

2024-08-19T00:20:04

在线演示

Trail:日期时间了解有关现代日期时间 API 的更多信息。


-2
投票

试试这个:

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime

val dateTimeString = "2024-08-19 00:20:04.0 +2:00"
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S XXX")

try {
  val zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter)
  val localDateTime = zonedDateTime.toLocalDateTime

  println(localDateTime)
} catch {
  case e: Exception => e.printStackTrace()
}
© www.soinside.com 2019 - 2024. All rights reserved.