1

I want to show a date string in this format: Jun 27, 2012. I did this:

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyy");
String date = sdf.format(Calendar.getInstance());

But it gives me this:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

What am I doing wrong?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90

2 Answers2

10
sdf.format()

Takes a Date, not a Calendar object.

Leigh
  • 28,765
  • 10
  • 55
  • 103
evanwong
  • 5,054
  • 3
  • 31
  • 44
  • 2
    +1 Which is why it gives `IllegalArgumentException: Cannot format given Object as a Date` – Peter Lawrey Jun 27 '12 at 14:58
  • Anyway, the output is "jun 27, 2012" instead of "Jun 27, 2012". Is there a way to capitalize the first letter by means of the date formatter? – Charlie-Blake Jun 27 '12 at 14:58
  • 2
    @santirivera92: What locale are you using, and what do you *want* to use? For example, what would you expect for April? (My guess is that at the moment you'll get "avr" for "Avril".) – Jon Skeet Jun 27 '12 at 15:01
  • I have not declared any locale, but in my locale I'd get "abr" for "Abril", I'm from Spain – Charlie-Blake Jun 27 '12 at 15:43
9

You can not use Calendar.getInstance(), since the param for same is date and not calender instance. Just change the param to getTime()

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
String date = sdf.format(Calendar.getInstance().getTime());
Umesh Aawte
  • 4,590
  • 7
  • 41
  • 51