java.lang.IllegalArgumentException: Bad class: class java.util.GregorianCalendar
Asked Answered
P

2

45

I received this exception while using GregorianCalendar

java.lang.IllegalArgumentException: Bad class: class java.util.GregorianCalendar

Who know how to fix,

Please help me.

p/s : I used the following code :

Calendar someDate = GregorianCalendar.getInstance();
        someDate.add(Calendar.DAY_OF_YEAR, -7);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = dateFormat.format(someDate);

UPDATED I should be use this line to achieve the date time :

String formattedDate = dateFormat.format(someDate.getTime());

Pay answered 4/6, 2014 at 15:25 Comment(4)
If using eclipse: remove your imports, then do ctrl+Shift+OPaperback
huh? don't understand your case clearly. But after do thing as u said. still can not fix issuPay
Same What i want to ask :PScoundrelly
Yeah, many people need it :pPay
P
96

A Calendar can't be directly formatted, you need to get the Date from the Calendar, like this:

String formattedDate = dateFormat.format(someDate.getTime());
Paperback answered 4/6, 2014 at 15:35 Comment(7)
Actually it's not so good to call a method like this, signature: public final Date getTime() (I expect get date method which will return time :)Stable
@Stable What do you mean?Paperback
I mean calendar methods naming are not so good, getTime should return Time (i.e. 12:00), getDate shoud return Date (i.e. 2016-01-01), but now in java getTime() returns a Date instance.Stable
Calendar is not a subclass of Date. Why does this compile on Android?Koffman
@peter: Calendar.getTime() retrieves the Calendar as a Date.Paperback
@Paperback I mean SimpleDateFormat::format(Calendar). It compiled on my Android app but then it threw a a runtime exceptionKoffman
@peter. SimpleDateFormat extends Format which has format(Object).Paperback
H
2

As one of the answers here: Using GregorianCalendar with SimpleDateFormat says "A SimpleDateFormat, as its name indicates, formats Dates."

So, try this:

String formattedDate = dateFormat.format(someDate.getDate());
Heterochromatin answered 4/6, 2014 at 15:35 Comment(1)
someDate.getTime() will be return Date, not someDate.getDate()Pay

© 2022 - 2024 — McMap. All rights reserved.