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

20,496

Solution 1

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

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

Solution 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());
Share:
20,496

Related videos on Youtube

Huy Tower
Author by

Huy Tower

​Huy Tower --- Flutter Developer | Senior Android Developer --- Skype: huytower Location : Ho Chi Minh, Viet Nam

Updated on July 09, 2022

Comments

  • Huy Tower
    Huy Tower almost 2 years

    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());

    • wvdz
      wvdz about 10 years
      If using eclipse: remove your imports, then do ctrl+Shift+O
    • Huy Tower
      Huy Tower about 10 years
      huh? don't understand your case clearly. But after do thing as u said. still can not fix issu
    • Pratik Butani
      Pratik Butani almost 9 years
      Same What i want to ask :P
    • Huy Tower
      Huy Tower almost 8 years
      Yeah, many people need it :p
  • Huy Tower
    Huy Tower almost 10 years
    someDate.getTime() will be return Date, not someDate.getDate()
  • xwild
    xwild over 8 years
    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 :)
  • wvdz
    wvdz over 8 years
    @xwild What do you mean?
  • xwild
    xwild over 8 years
    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.
  • Peter Chaula
    Peter Chaula over 7 years
    Calendar is not a subclass of Date. Why does this compile on Android?
  • wvdz
    wvdz over 7 years
    @peter: Calendar.getTime() retrieves the Calendar as a Date.
  • Peter Chaula
    Peter Chaula over 7 years
    @wvdz I mean SimpleDateFormat::format(Calendar). It compiled on my Android app but then it threw a a runtime exception
  • wvdz
    wvdz over 7 years
    @peter. SimpleDateFormat extends Format which has format(Object).