无法使用LocalDateTime解析日期

时间:2016-01-12 18:00:34

标签: java parsing datetime format

我尝试使用Java8 LocalDateTime解析日期字符串但没有成功。

例外情况是: DateTimeParseException:Text' 28-APR-2015 01:25:00 PM'无法在索引3解析

要解析的字符串是: 28-APR-2015 01:25:00 PM ,我目前使用的模式是 dd-LLL-yyyy hh:mm: ss a

我哪里错了?

谢谢

添加示例代码:

String text = "28-APR-2015 01:25:00 PM";
DateTimeFormatter fromatter = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a");
try {
        String out = LocalDateTime.parse(text, formatter)
        System.out.println(out);
    } catch (DateTimeParseException e) {
        e.printStackTrace();
    }

使用@Florin的回复解决:

    DateTimeFormatter tertiaryFormatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive().parseLenient().appendPattern("dd-LLL-yyyy hh:mm:ss a").toFormatter();

2 个答案:

答案 0 :(得分:1)

LLL英文将 Apr

英语中的

asList("MMM", "LLL").forEach(ptrn -> System.out.println(ptrn + ": " + ofPattern(ptrn, Locale.ENGLISH).format(Month.APRIL)) ); Locale.setDefault(Locale.ENGLISH); String textM = "28-Apr-2015 01:25:00 PM"; DateTimeFormatter formatterM = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a"); System.out.println(LocalDateTime.parse(textM, formatterM)); String textL = "28-4-2015 01:25:00 PM"; DateTimeFormatter formatterL = DateTimeFormatter.ofPattern("dd-LLL-yyyy hh:mm:ss a"); System.out.println(LocalDateTime.parse(textL, formatterL)); 4

请运行此代码段 - 它会向您解释很多:

DateTimeFormatter

如果您需要使用 APR ,则需要使用DateTimeFormatterBuilder构建自己的parseCaseInsensitive并设置body { margin: 0px; padding: 0px; background-color: #fff; } .marquee { margin: 10px; padding: 10px; } span { display: inline-block; margin:0px; padding:0px; } .container{ display: flex; justify-content: center; list-style-type: none; } .ind-cont { background-color: #000; width: 200px; height: 100px; margin: 0px; padding:0px; } .txtcolor { color: #fff; } .txtcolorb { color: #aaa; } .ind-name { margin: 20px; } .capital { float: right; margin: 20px; } .floatright { float: right; margin: 10px; margin-right: 20px; } .one-share { margin: 10px; margin-left: 20px; }选项。

答案 1 :(得分:0)

The problem is because of your time pattern issue. you need make sure your time format could matching with the pattern.

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

enter image description here