why do I get wrong month when parsing with java ca

2019-03-03 12:08发布

问题:

Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Calendar calendar = Calendar.getInstance()
calendar.setTime(fakeDate);
int currentMonth = calendar.get(Calendar.MONTH);

I get currentMonth == 6 instead of 7.

why is that?

回答1:

Because Calendar.MONTH is ZERO based. Why?

Check the docs: (always)

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.



回答2:

As the doc says - Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

So try something like this

int currentMonth = calendar.get(Calendar.MONTH)+1;

Because calendar.get(Calendar.MONTH) shall give you (currentMonthValue-1) as the value of january starts with 0



回答3:

It should be

int currentMonth = calendar.get(Calendar.MONTH)+1;