在 Java 中将字符串解析为 LocalDateTime

Parse a String to LocaDateTime in Java

考虑一个字符串 "2022-03-23 21:06:29.4933333 +00:00"。 如何将上述 DateTimeOffset 字符串解析为 Java 中的 LocalDateTime?

我尝试使用以下 DateTimeFormatter,但格式似乎不正确:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss\[.nnnnnnn\] \[+|-\]hh:mm\]");

LocalDateTime dateTime = LocalDateTime.parse(timestamp, formatter)

首先,手头有 JavDocs for DateTimeFormatter,这将真正帮助确定您需要哪些说明符

首先要做的是将文本解析为 ZonedDateTimeLocalDateTime 不会解析带有时区的输入值 (AFAIK),您“可能”能够强制它,但有什么意义呢?

String text = "2022-03-23 21:06:29.4933333 +00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSS z");
ZonedDateTime zdt = ZonedDateTime.parse(text, formatter);
System.out.println(zdt);

这会打印...

2022-03-23T21:06:29.493333300Z

现在您可以使用 ZonedDateTime#toLocalDateTime,但这不会考虑 user/computer 的当前时区。

如果您需要将 ZonedDateTime 转换为 LocalDateTime,最好在 away 中这样做,这将转换时间(如果需要,还包括日期)以最好地表示当前时间的时间zone(好吧,我打错了)

例如,将输入值转换为我当前的时区(+11 小时)将如下所示...

ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime currentZDT = zdt.withZoneSameInstant(currentZone);
System.out.println(currentZDT);
LocalDateTime ldt = currentZDT.toLocalDateTime();
System.out.println(ldt);

这将打印...

2022-03-24T08:06:29.493333300+11:00[Australia/Melbourne]
2022-03-24T08:06:29.493333300

这意味着格林奇 (GMT) 的 3 月 23 日 9:06pm,我居住的地方是 3 月 24 日 8:06am。

现在您可以使用不同的 ZoneId 转换为 TimeZone,这不是当前的计算机 TimeZone,但我会把它留给您来试验 (例如,我使用 作为示例的基础)

您需要创建自定义 DateTimeFormatter:

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public class Main {
    public static void main(String args[]){
        String dateString = "2022-03-23 21:06:29.4933333 +00:00";

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(java.time.format.DateTimeFormatter.ISO_LOCAL_TIME)
                .appendLiteral(' ')
                .appendOffsetId()
                .toFormatter();

        //In case of OffSet matter, retaining the instant
        LocalDateTime localDateTimeSavePointOfTime = OffsetDateTime.parse(dateString, formatter).withOffsetSameInstant(OffsetDateTime.now().getOffset()).toLocalDateTime();

        //In case OffSet does not matter we can skip it
        LocalDateTime localDateTimeSkipOffSet = LocalDateTime.parse(dateString, formatter);

    }
}