【发布时间】:2020-12-15 04:25:54
【问题描述】:
尝试将字符串转换为 localDateTime 并查看日期是否超过一年。我知道它应该工作,但它不工作。在索引“i”处获取解析异常
LocalDateTime currentTimeLastYear = LocalDateTime.now().minusYears(1);
String pattern = "MM/dd/yyyy'T'HH:mm:s";
// ex "8/30/2019T15:51:5"
String queryToDate = query.getDateRange().getToDate();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.parse(queryToDate, formatter);
System.out.println(localDateTime);
if(localDateTime.isBefore(currentTimeLastYear)) {
return true;
}
【问题讨论】:
-
日期字符串的格式显然不是
MM/dd/yyyy。两个Ms 表示月份为个位数时会有前导0。 -
使用
String pattern = "M/dd/yyyy'T'HH:mm:s";