从包含T的字符串中解析日期

时间:2019-03-06 00:17:29

标签: java datetime java-8

如何将日期2020-08-05T00:00:00.000-05:00解析为MM/dd/yyyy h:mmaa

我尝试了

String str = "2020-08-05T00:00:00.000-05:00";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mmaa");
    System.out.println(LocalDateTime.parse(str, formatter));

DateTimeFormatter inputFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
    DateTimeFormatter outputFormatter1 = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mmaa", Locale.US);

    LocalDate date = LocalDate.parse("2020-08-05T00:00:00.000-05:00", inputFormatter1);
    String formattedDate = outputFormatter1.format(date);
    System.out.println(formattedDate);

但出现异常-

Exception in thread "main" java.lang.IllegalArgumentException: Too many pattern letters: a
at java.time.format.DateTimeFormatterBuilder.parseField(DateTimeFormatterBuilder.java:1763)
at java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1602)
at java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1570)
at java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:536)

更新1:

我尝试了以下代码-

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mmaa", Locale.US);
    LocalDate date = LocalDate.parse("2020-08-05T00:00:00.000-05:00", inputFormatter);
    String formattedDate = outputFormatter.format(date);
    System.out.println(formattedDate);

但是现在在outputFormatter出现相同错误时-

Exception in thread "main" java.lang.IllegalArgumentException: Too many pattern letters: a

0 个答案:

没有答案