【发布时间】:2021-05-20 09:00:40
【问题描述】:
我帮助设置了一个函数来获取两个字符串并将它们合并到一个日期对象中。 Java - Take two strings and combine into a single date object
在尝试解析 6 月 1 日之前一直运行良好,然后出现以下错误
Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '1st June' could not be parsed, unparsed text found at index 7
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at Timetable.ClassManager.parseDate(ClassManager.java:201)
at Timetable.GoogleAPI.loadClasses(GoogleAPI.java:133)
at Timetable.ClassManager.loadClasses(ClassManager.java:58)
函数的代码是
public LocalDateTime parseDate(String strDate, String strTime) {
strTime = strTime + ":00";
System.out.println("Date: " + strDate);
System.out.println("Time: " + strTime);
LocalDate date = LocalDate.now();
DateTimeFormatter dtfForDate = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseDefaulting(ChronoField.YEAR, date.getYear())
.appendPattern("d['th']['st']['rd']['nd'] MMM")
.toFormatter(Locale.ENGLISH);
DateTimeFormatter dtfForTime = DateTimeFormatter.ofPattern("H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDate.parse(strDate, dtfForDate)
.atTime(LocalTime.parse(strTime, dtfForTime));
System.out.println("Local Date Time: " + ldt);
return ldt;
}
这两张照片给了我
Date: 1st June
Time: 9:15:00
我需要能够同时处理完整的月份名称和月份缩写,即 March 设置为 Mar,April 设置为 Apr。
【问题讨论】:
-
好吧,6 月 1 日不是时间的有效格式。这将是问题
-
您可能只需要
MMMM来获取完整的月份名称。当您解析 5 月的日期时,它没有区别,因为完整的月份名称和月份缩写都是英文的May,所以直到您发现Jun和June之间的区别时才发现您的错误。 -
如果需要接受
Mar、Apr、May和June,镀金方案是下半段序数已经用过的appendText(TemporalField, Map<Long, String>)方法答案。有了这个,您可以准确地控制哪些月份是完整的,哪些是缩写的。