[英]Cannot parse date with LocalDateTime
I'm trying to parse a date string using Java8 LocalDateTime without any success. 我正在尝试使用Java8 LocalDateTime解析日期字符串,但没有成功。
The exception is: DateTimeParseException: Text '28-APR-2015 01:25:00 PM' could not be parsed at index 3 例外是: DateTimeParseException:无法在索引3处解析文本'28 -APR-2015 01:25:00 PM'
The string to parse is: 28-APR-2015 01:25:00 PM and the pattern I'm currently using is dd-LLL-yyyy hh:mm:ss a 要解析的字符串是: 28-APR-2015 01:25:00 PM ,我当前使用的模式是dd-LLL-yyyy hh:mm:ss a
Where am I wrong? 我哪里错了?
Thank you 谢谢
Adding example code: 添加示例代码:
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();
}
Solved using the response from @Florin using: 通过使用@Florin的响应来解决:
DateTimeFormatter tertiaryFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient().appendPattern("dd-LLL-yyyy hh:mm:ss a").toFormatter();
MMM
in English will be Apr 英文
MMM
为4月
LLL
in English will be 4 英语
LLL
将是4
Please run this snippet - it will explain you a lot: 请运行此代码段-它会为您提供很多解释:
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));
If you need to use APR then you need to build your own DateTimeFormatter
using DateTimeFormatterBuilder
and set parseCaseInsensitive
option. 如果你需要使用APR,那么你需要建立自己的
DateTimeFormatter
使用DateTimeFormatterBuilder
并设置parseCaseInsensitive
选项。
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 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.