【问题标题】:How to parse Javascript Date to Java LocalDateTime with day of the week如何使用星期几将 Javascript 日期解析为 Java LocalDateTime
【发布时间】:2022-01-26 20:35:33
【问题描述】:

我正在尝试将存储在 mongoDb 中的 Javascript 日期转换为 Java LocalDateTime ISO_DATE_TIME,但我一直遇到 ParseException,我无法弄清楚我的代码为什么会出错。首先,代码:

解析器:

public static final class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

        public static final StringToLocalDateTimeConverter INSTANCE = new StringToLocalDateTimeConverter();

        private StringToLocalDateTimeConverter() {}

        @Override
        public LocalDateTime convert(String source) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
            return StringUtil.isNullOrEmpty(source) ? null : LocalDateTime.parse(source, formatter);
        }
    }

传入的日期格式为“Thu Oct 07 2021 21:29:36 GMT+0000 (Coordinated Universal Time)”

我收到的错误是:

getUserById() 中出现异常,原因 = 'java.time.format.DateTimeParseException: Text 'Thu Oct 07 2021 21:29:36 GMT+0000 (Coordinated Universal Time)' 无法在索引 0 处解析' 和异常 = '未能从类型 [java.lang.String] 转换为类型 [java.time.LocalDateTime] 值'Thu Oct 07 2021 21:29:36 GMT+0000 (Coordinated Universal Time)';嵌套异常是 java.time.format.DateTimeParseException: Text 'Thu Oct 07 2021 21:29:36 GMT+0000 (Coordinated Universal Time)' could not be parsed at index 0'

解析器似乎不知道如何处理一周的前一天。任何建议将不胜感激!

【问题讨论】:

  • 看看你传递给DateTimeFormatter.ofPattern的模式。它看起来 没有 像您要求它解析的值。
  • 抱歉,如果我把它弄反了,但我认为这是我想要接收的输出格式?
  • 没有。您正在尝试解析为 LocalDateTime。这只是一个值 - 它没有 格式。 (如果要将其转换为默认格式以外的字符串,则需要在该点指定格式。)您要求使用 DateTimeFormatter解析传入的value,这意味着它的模式必须匹配传入的值。
  • (如果您可以影响存储在 MongoDB 中的格式,我会这样做 - 这是一种可怕的日期/时间格式。但那是另一回事。)
  • 嗯,明白了!我将研究使用 RFC_1123_DATE_TIME 作为格式化程序。看起来我的想法倒退了。

标签: java datetime


【解决方案1】:

你有错误的日期格式模式来解析你的日期字符串。

String parsePattern = "EEE MMM dd yyyy HH:mm:ss O (zzzz)";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(parsePattern);


String dateString = "Wed Jan 26 2022 22:33:07 GMT+1 (Central European Standard Time)";
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
System.out.println(dateTime); // result 2022-01-26T22:33:07

【讨论】:

  • 由于 RFC_1123_DATE_TIME 最终没有作为一个合适的格式化程序工作,我对你的进行了一次尝试,它肯定让我走上了正确的轨道!再加上 Jon Skeet 的回答,我最终使用了String parsePattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'xx '('zzzz')'";
猜你喜欢
  • 2020-10-23
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2017-01-03
  • 2015-12-25
  • 1970-01-01
相关资源
最近更新 更多