Java Calendar date error

2020-05-03 12:01发布

Can anyone please help me understand why I am getting different month values for

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");    
System.out.println(dateFormat.format(cal.getTime()) 
                   + "--" 
                   + cal.get(Calendar.MONTH));

Surprisingly displays

09/09/2012--8

5条回答
We Are One
2楼-- · 2020-05-03 12:13

Your likely problem is that Calendar uses a zero-based index for months. So the format correctly outputs 9 for September, but the getter returns 8.

Is this stupid and inconsistent of Calendar? Yes! Use the Joda-Time API for working with dates and times instead. As far as I'm aware, it's currently the de-facto standard until JSR 310 comes around.

查看更多
何必那么认真
3楼-- · 2020-05-03 12:18

The other answers are correct. The java.util.Calendar class uses zero-based counting for month numbers. One of many reasons to avoid using the java.util.Date/Calendar classes.

This kind of work is easier with the Joda-Time 2.3 library. Thankfully it sensibly uses one-based counting such as January = 1, December = 12.

java.util.Calendar cal = java.util.Calendar.getInstance();

// Though not required here for this one purpose, it's better to specify a time zone than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( cal.getTime(), timeZone );

// Extract month. Note how these two lines call similar sounding methods that are actually quite different.
// One returns a primitive int value. The other returns an object of nested class DateTime.Property.
int monthNumber = dateTime.getMonthOfYear();
String monthName = dateTime.monthOfYear().getAsText( Locale.FRENCH );

Dump to console…

System.out.println( "dateTime: " + dateTime );
System.out.println( "monthNumber: " + monthNumber );
System.out.println( "monthName: " + monthName );

When run…

dateTime: 2014-02-10T02:58:35.386-05:00
monthNumber: 2
monthName: février
查看更多
smile是对你的礼貌
4楼-- · 2020-05-03 12:27

In Calendar class, MONTH start from index 0. So, January is 0, February is 1, and hence September is 8.

P.S.: - That's true that this is an Inconsistency in Calendar class, so I would suggest you to take a look at Joda-Time API to make your life easier while working with date-time data.

查看更多
We Are One
5楼-- · 2020-05-03 12:31

Calendar.MONTH return 0-based values i.e. JANUARY is represented with 0. That way SEPTEMBER is 8.

查看更多
趁早两清
6楼-- · 2020-05-03 12:34

Months in Calendar starts in 0

查看更多
登录 后发表回答