简体   繁体   English

为什么用Java日历解析时会出现错误的月份

[英]why do I get wrong month when parsing with java calendar

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. 我得到currentMonth == 6而不是7。

why is that? 这是为什么?

Because Calendar.MONTH is ZERO based. 因为Calendar.MONTH是基于零的。 Why ? 为什么

Check the docs : (always) 检查文档 :(始终)

Field number for get and set indicating the month. get和set的字段号指示月份。 This is a calendar-specific value. 这是日历特定的值。 The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0 ; 公历和朱利安历法中的第一年是1月,零 the last depends on the number of months in a year. 最后一个取决于一年中的月份数。

As the doc says - Field number for get and set indicating the month. 正如文档所说-get和set的字段号指示月份。 This is a calendar-specific value. 这是日历特定的值。 The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; 阳历和朱利安历中的第一月是一月,即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 因为calendar.get(Calendar.MONTH)应该给您(currentMonthValue-1),因为一月的值从0开始

它应该是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM