有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

DateTimeFormatter的java日期格式问题

我有以下格式的日期:1/1/2020 3:4:7 AM我正在尝试使用DateTimeFormatter格式化它

我有以下带有格式化程序的代码来解析它,但它不起作用

LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM", DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));

我得到以下例外情况:

java.time.format.DateTimeParseException: Text '1/1/2020 3:4:7 AM' could not be parsed at index 0

有人能帮我吗


共 (4) 个答案

  1. # 1 楼答案

    根据documentation of DateTimeFormatter报告:

    Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.

    通过反向推理,您可以尝试改用此格式化程序:

    DateTimeFormatter.ofPattern("M/d/yyyy h:m:s a")
    
  2. # 2 楼答案

    两个独立的问题:

    错误计数

    您正在使用例如MM,这是一个显式的:始终是完整的数字量,零填充。你的字符串不是那样的,只是数字。所以,让它M/d/uuuu h:m:s a

    编辑:将yyyy更改为uuuu,谢谢,@deHaar。推理:yyyy或uuuu很少重要,但请注意,这意味着需要4位数字。这种差异在0:uuuu变为负值之前的几年内就开始存在了,yyyy没有,并且希望您使用例如GG,这样您得到的是44 BC而不是-44。这样一来,uuuu就更正确了,尽管通常不会出现差异

    缺少区域设置

    第二个问题是,您几乎不应该使用这个版本的ofPattern,因为它有一个bug,您无法通过单元测试发现它,这使得这个bug“更重”数千倍,因此,这是一个真正的问题

    您需要指定区域设置。如果没有它,“AM”将无法解析,除非您的平台默认语言环境是英语

    把它放在一起

    LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM",
      DateTimeFormatter.ofPattern("M/d/uuuu h:m:s a", Locale.ENGLISH));
    

    效果很好

  3. # 3 楼答案

    在您的代码片段中:

    LocalDateTime
        .parse("1/1/2020 3:4:7 AM", DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));
    
    • 1-不匹配MM
    • 1-不匹配dd
    • 3-不匹配hh
    • 4-不匹配mm
    • 7-不匹配ss

    也就是说,格式化程序模式部分(例如MM)的长度与字符串文本中的相应部分(例如1)的长度不匹配

    您可以通过几种方式匹配它们,例如,您可以更改字符串文本以匹配格式化程序模式,也可以通过其他方式进行匹配

    您可以尝试以下方法:

    LocalDateTime
        .parse("01/01/2020 03:04:07 AM", DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));
    

    此外,请看一下Pattern Letters and Symbols

  4. # 4 楼答案

    1. 日期和时间组件(月、日、年、小时、分钟和秒)使用单个字母

    2. 您还可以使格式化程序以不区分大小写的方式(例如am、am、am)处理模式,如下所示:

      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) {
               // Formatter to handle the pattern in case insensitive way (e.g. am, AM, Am)
              DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                                  .parseCaseInsensitive()
                                                  .appendPattern("M/d/u h:m:s a")
                                                  .toFormatter(Locale.ENGLISH);
              LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM", formatter);
              System.out.println(date);
          }
      }
      

    输出:

    2020-01-01T03:04:07