无法使用 LocalDateTime 解析日期?

Unable to parse date using LocalDateTime?

我正在尝试使用 DateTimeFormatter 解析日期字符串。我收到以下异常:

日期格式错误 10.10.2020 12:00:00 java.time.format.DateTimeParseException:无法在索引 2

处解析文本“10.10.2020 12:00:00”
 String date="10.10.2020 12:00:00";
  
 String dateTimeFormat = "MM/dd/yyyy HH:mm:ss a";
 String exportTimeZone = "UTC";

 DateTimeFormatter format = DateTimeFormatter.ofPattern(dateTimeFormat);

 LocalDateTime impDateTime = LocalDateTime.parse(StringUtils.trim(date), format);
 ZonedDateTime dateInUtc = ZonedDateTime.ofInstant(impDateTime.atZone(ZoneId.of(exportTimeZone)).toInstant(), ZoneId.systemDefault());
 return format.format(dateInUtc);
              

任何帮助将不胜感激?

您在格式中使用了 / 而不是 .。此外,当您使用 HH 时,这意味着它是 24 小时格式,而不是 am/pm,因此您不应在格式中使用 aHH。此外,您的日期时间字符串中没有 am/pm,因此在格式中使用 a 无论如何都会导致错误。

演示:

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

public class Main {
    public static void main(String[] args) {
        String dateTime = "10.10.2020 12:00:00";

        // Define the format
        DateTimeFormatter format = DateTimeFormatter.ofPattern("MM.dd.yyyy HH:mm:ss");

        // Parse date-time as using the defined format
        LocalDateTime impDateTime = LocalDateTime.parse(dateTime, format);

        // Get date-time at UTC
        ZonedDateTime dateTimeInUtc = impDateTime.atZone(ZoneId.of("Etc/UTC"));

        // Display
        System.out.println(dateTimeInUtc);
    }
}

输出:

2020-10-10T12:00Z[Etc/UTC]

让我们读一下消息:

java.time.format.DateTimeParseException: Text '10.10.2020 12:00:00' could not be parsed at index 2

索引从 0 开始,因此 10.10.2020 12:00:00 中的索引 2 是第一个点(句点、点)所在的位置。所以 Java 无法解析那个点。想知道为什么,我们看格式模式string

中对应的地方
String dateTimeFormat = "MM/dd/yyyy HH:mm:ss a";

所以月份 10 已被成功解析,接下来是格式化程序所期望的 — 斜线。斜杠和点之间的差异解释了异常。

进一步的提示:当获取用于正确解析的格式模式字符串变得非常重要时,请先尝试格式化已知日期:

    System.out.println("To be parsed: " + date);
    LocalDateTime knownDateTime = LocalDateTime.of(2020, Month.OCTOBER, 10, 12, 0);
    System.out.println("Formatted:    " + knownDateTime.format(format));

这种情况下的输出:

To be parsed: 10.10.2020 12:00:00
Formatted:    10/10/2020 12:00:00 PM

这种打印方式可以更容易地发现我们得到的内容与格式化程序期望解析的内容之间的差异。