46

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

Huy Tower
  • 7,769
  • 16
  • 61
  • 86

2 Answers2

97

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

String formattedDate = dateFormat.format(someDate.getTime());
wvdz
  • 16,251
  • 4
  • 53
  • 90
  • 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 :) – xwild Mar 24 '16 at 08:51
  • @xwild What do you mean? – wvdz Mar 24 '16 at 15:10
  • 3
    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. – xwild Mar 25 '16 at 05:24
  • `Calendar` is not a subclass of `Date`. Why does this compile on Android? – Peter Chaula Feb 20 '17 at 09:45
  • @peter: `Calendar.getTime()` retrieves the `Calendar` as a `Date`. – wvdz Feb 20 '17 at 12:23
  • @wvdz I mean `SimpleDateFormat::format(Calendar)`. It compiled on my Android app but then it threw a a runtime exception – Peter Chaula Feb 20 '17 at 13:30
  • 2
    @peter. `SimpleDateFormat` extends `Format` which has `format(Object)`. – wvdz Feb 20 '17 at 13:39
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());
Community
  • 1
  • 1
Zoran
  • 1,484
  • 1
  • 10
  • 13