why do I get wrong month when parsing with java ca

2019-03-03 12:06发布

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?

3条回答
何必那么认真
2楼-- · 2019-03-03 12:12

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楼-- · 2019-03-03 12:29

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.

查看更多
Evening l夕情丶
4楼-- · 2019-03-03 12:32

It should be

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

查看更多
登录 后发表回答