[英]Convert String to java.time.localDate
1.way 1.方式
LocalDate ld = LocalDate.parse(reservationDTO.getReservationDate());
2.way 2种方法
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(reservationDTO.getReservationDate(),
formatter);
3.way 3.路
LocalDate localDate = LocalDate.parse(reservationDTO.getReservationDate());
I try convert String to java.time.localDate but for this 3 ways i have error我尝试将 String 转换为 java.time.localDate 但对于这 3 种方式我有错误
java.time.format.DateTimeParseException: Text '2018-7-11' could not be parsed at index 5
Pls notice this line请注意这一行
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Specially format yyyy-MM-dd
特殊格式
yyyy-MM-dd
You configure to pass a Date of Format with 4 Char of year, 2 Char of Month and 2 Char of Date .您配置为传递带有年份的 4 个字符、月份的 2 个字符和日期的 2 个字符的格式日期。 But you are passing only 1 Digit in month.
但是您每个月只传递 1 位数。
So what you need to pass is 2018-07-11
所以你需要通过的是
2018-07-11
If you cannot change reservationDTO.getReservationDate()
you need to use only one M
如果你不能改变
reservationDTO.getReservationDate()
你只需要使用一个M
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd");
LocalDate dateTime = LocalDate.parse(reservationDTO.getReservationDate(),
formatter);
As you can see in the javadoc M/L
matches with 7, 07, Jul, July, J正如您在javadoc
M/L
与 7, 07, Jul, July, J 匹配中所见
Otherwise, if you can change reservationDTO.getReservationDate()
just transform 2018-7-11
into 2018-07-11
否则,如果您可以更改
2018-7-11
reservationDTO.getReservationDate()
只需将2018-7-11
转换为2018-07-11
The date string you are trying to parse is not proper.您尝试解析的日期字符串不正确。 Date should be 'yyyy-MM-dd' eg '2018-07-24'.
日期应为“yyyy-MM-dd”,例如“2018-07-24”。 You are trying to parse the string 2018-7-24
您正在尝试解析字符串 2018-7-24
i think this example will resolve your problem.我认为这个例子会解决你的问题。
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.