【问题标题】:How do I parse "Nov 20, 2016 12:00:00 AM" to LocalDateTime?如何将“2016 年 11 月 20 日 12:00:00 AM”解析为 LocalDateTime?
【发布时间】:2020-12-03 00:21:01
【问题描述】:

我发现了非常有趣的错误或类似的东西。

我使用这种日期格式MMM d, yyyy hh:mm:ss a,它会像这样打印日期

Aug 13, 2020 01:19:50 pm

但是,当我将 Nov 20, 2016 12:00:00 AM 解析为 LocalDateTime 时,它会抛出异常

java.time.format.DateTimeParseException: Text 'Nov 20, 2016 12:00:00 AM' could not be parsed at index 22.

在我将“AM”更改为“am”后,它可以完美运行! 所以 LocalDateTime 因为大写 a̶p̶e̶s̶ 字母而无法解析日期? 我怎样才能解决这个问题,而不是将'AM'替换为'am'和'PM'替换为'pm'

编辑

SimpleDateTime 格式没有这个问题,他忽略了 a̶p̶e̶s̶ 字母寄存器(我的意思是大写或小写)并且我不想将Date 转换为LocalDateTime

编辑 2

MMM d, yyyy hh:mm:ss Areplace 'a' to 'A' 也没有用

【问题讨论】:

  • 啊哈哈,不好意思,有点意思,我以为“猿”翻译成“字母”,现在才知道翻译成猴子,真是愚蠢的误会)

标签: java datetime-format localdatetime datetimeformatter


【解决方案1】:

您需要以不区分大小写的方式对其进行解析。此外,请确保使用英语语言环境(例如 Locale.ENGLISHLocale.US 等),因为元素名称在相应的语言环境中使用本地化字符串表示。

演示:

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

public class Main {
    public static void main(String[] args) {
        // Given date-time string
        String strDateTime = "Nov 20, 2016 12:00:00 AM";

        // Define the formatter
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .parseCaseInsensitive()
                                        .appendPattern("MMM d, u h:m:s a")                                       
                                        .toFormatter(Locale.ENGLISH);                                     

        // Parse the given date-time into LocalDateTime using formatter
        LocalDateTime ldt = LocalDateTime.parse(strDateTime, formatter);

        System.out.println(ldt);
    }
}

输出:

2016-11-20T00:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多