IllegalArgumentException while converting java.util.Date to org.joda.time.DateTime

StackOverflow https://stackoverflow.com/questions/16883899

  •  30-05-2022
  •  | 
  •  

문제

I want to calculate the number of days, months and years between two Dates so i use JodaTime. I can get the result perfectly if my dates are in type of org.joda.time.DateTime. However the date inserted by the user is in type of Date ( format "yyy-mm-dd" ) and i use this type and this format in the whole project. so I write this code :

 Date d1=new Date("2013-09-11"); 
       Date d2=new Date("2014-12-12"); 
       DateTime dt1 = new DateTime(d1);
       DateTime dt2=new DateTime(d2);
       CalculCalendar clcd=new CalculCalendar(dt1,dt2);
       System.out.println(clcd.getNbjours(dt1, dt2)+" "+ clcd.getNbmois(dt1, dt2)+" "+ clcd.getNbyears(dt1, dt2));

When I run it, I get this error :

Exception in thread "main" java.lang.IllegalArgumentException
    at java.util.Date.parse(Unknown Source)
    at java.util.Date.<init>(Unknown Source)
    at CalendarDemo.main(CalendarDemo.java:50)

CalendarDemo.java:50 refers to : Date d2=new Date("2014-12-12");

How to resolve this problem without changing this format ?

도움이 되었습니까?

해결책

Your problem isn't in conversion form JDK Date to Joda DateTime at all. It's in parsing a string to a JDK Date.

Date d2=new Date("2014-12-12"); 

is a deprecated constructor call. You probably should either use a DateFormat to parse your datestring into a Date, or parse it straight to Joda's DateTime using its parse method and a similar DateTimeFormatter.

These parsing methods allow you to specify the format you're expecting explicitly rather than depending on the default Date.parse(), which tries to figure out the format from the data. Specifically why it's failing in this instance I can't say, but this is code you just shouldn't be using anyway. It's been deprecated for years.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top