java-8 – java. time. format. Datetimeparseexception: cannot parse text at index 3

I use Java 8 to parse the date and find the difference between the two dates

This is my clip:

String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY",en);
LocalDate  d1 = LocalDate.parse(date1,df);
LocalDate  d2 = LocalDate.parse(date2,df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);

When I run, I get an error:

Solution

The following codes are valid The problem is that you use "Jan" instead of "Jan"

String date1 ="01-Jan-2017";
  String date2 = "02-Feb-2017";

  DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
  LocalDate  d1 = LocalDate.parse(date1,df);
  LocalDate  d2 = LocalDate.parse(date2,df);

  Long datediff = ChronoUnit.DAYS.between(d1,d2);

Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>