![](/img/trans.png)
[英]Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDate'
[英]Convert String to java.time.localDate
1.方式
LocalDate ld = LocalDate.parse(reservationDTO.getReservationDate());
2种方法
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(reservationDTO.getReservationDate(),
formatter);
3.路
LocalDate localDate = LocalDate.parse(reservationDTO.getReservationDate());
我尝试将 String 转换为 java.time.localDate 但对于这 3 种方式我有错误
java.time.format.DateTimeParseException: Text '2018-7-11' could not be parsed at index 5
请注意这一行
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
特殊格式yyyy-MM-dd
您配置为传递带有年份的 4 个字符、月份的 2 个字符和日期的 2 个字符的格式日期。 但是您每个月只传递 1 位数。
所以你需要通过的是2018-07-11
如果你不能改变reservationDTO.getReservationDate()
你只需要使用一个M
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd");
LocalDate dateTime = LocalDate.parse(reservationDTO.getReservationDate(),
formatter);
正如您在javadoc M/L
与 7, 07, Jul, July, J 匹配中所见
否则,如果您可以更改2018-7-11
reservationDTO.getReservationDate()
只需将2018-7-11
转换为2018-07-11
您尝试解析的日期字符串不正确。 日期应为“yyyy-MM-dd”,例如“2018-07-24”。 您正在尝试解析字符串 2018-7-24
我认为这个例子会解决你的问题。
String startDateString1 = "06/27/2007";
String startDateString2 = "2007-06-27";
DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy");
DateFormat df2 = new SimpleDateFormat("yyyy-mm-dd");
Date startDate1;
Date startDate2;
try {
startDate1 = df1.parse(startDateString1);
startDate2 = df2.parse(startDateString2);
LocalDate localDate1 = DateTimeUtils.toLocalDate(startDate1);
LocalDate localDate2 = DateTimeUtils.toLocalDate(startDate2);
System.out.println("localDate1:" + localDate1);
System.out.println("localDate2:" + localDate2);
System.out.println("Result: " + localDate1.isBefore(localDate2));
} catch (ParseException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.