T8Z
T8Z

Reputation: 691

Java Calendar and date format

I am confused by Java Calendar. Why does the exception occur when I run this code:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal2 = Calendar.getInstance();
System.out.println(dateFormat.format("todayDate : " + cal2.getTime()));

Here is Error:

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(DateFormat.java:301)
    at java.text.Format.format(Format.java:157)
    at test.CleanDirectory.main(CleanDirectory.java:20)

Upvotes: 0

Views: 3243

Answers (5)

Jens
Jens

Reputation: 69440

Because you are trying to format the string todayDate : <Date> to the Format "yyyy-MM-dd" what is not possible.

Change to

System.out.println("todayDate : " + dateFormat.format(cal2.getTime()));

Upvotes: 3

Basil Bourque
Basil Bourque

Reputation: 338584

The other answers are correct.

java.time

But you are using old outmoded troublesome classes. They have been supplanted by the java.time classes built into Java 8 and later.

String output = LocalDate.now( ZoneId.of( "America/Montreal" ) ).toString() ;

And you are ignoring the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by time zone.

If you omit the optional time zone argument, your JVM‘s current default time zone is applied. That default can change, even during runtime(!). So better to always specify your desired/expected time zone.

The output format you want is defined by the ISO 8601 standard. The java.time classes use these formats by default. So no need to define a formatting pattern.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
String output = today.toString();

Upvotes: 2

Harish
Harish

Reputation: 87

you have written the syntax wrongly while formatting it expecting the date object.

    System.out.println("todayDate : " + dateFormat.format(cal2.getTime()));

Upvotes: 1

madatx
madatx

Reputation: 81

The dateFormat.format takes instance of Date class. Probably you should write like this: System.out.println("todayDate : " + dateFormat.format(cal2.getTime()));

Upvotes: 3

Alex Shesterov
Alex Shesterov

Reputation: 27525

DateFormat.format expects a Date, you are passing a string with "todayDate :" prepended.

This should work:

System.out.println("todayDate : " + dateFormat.format(cal2.getTime()));

Upvotes: 1

Related Questions