techPackets
techPackets

Reputation: 4506

Java Calender class showing incorrect date

I am trying to fetch the current date with Calender class. I am running my web application on tomcat. But I don't understand why it is displaying the month day as 36. Below is my code.

SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));

Output

Current Date Time : 2014/02/36 04:30:14

Can anyone please explain how can a day be 36?

Does the Calender class shows the system time or the tomcat server runs its own time?

Upvotes: 1

Views: 320

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338594

Seems like the format you want is almost the standard ISO 8601 format. If so, you should know that the Joda-Time library that supplants the bundled java.util.Date/Calendar classes uses ISO 8601 format by default. So no need to define a formatter, Joda-Time already has one built-in.

The new java.time.* package bundled with Java 8 (and inspired by Joda-Time) also uses the ISO 8601 format by default.

Some example code using Joda-Time 2.3…

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime_Paris = new DateTime( 2014, 1, 24, 10, 0, 0, timeZone );

// Convert to UTC/GMT.
DateTime dateTime_UTC = dateTime_Paris.toDateTime( DateTimeZone.UTC );

System.out.println( "dateTime_Paris: " + dateTime_Paris );
System.out.println( "dateTime_UTC: " + dateTime_UTC );

When run…

dateTime_Paris: 2014-01-24T10:00:00.000+01:00
dateTime_UTC: 2014-01-24T09:00:00.000Z

Upvotes: 1

Rahul
Rahul

Reputation: 45060

That's because D represents the Day in year. You need to use dd instead which represents Day in month. Have a look at the docs on different patterns and their representation.

Upvotes: 5

Related Questions