Calendar returns wrong month

2019-01-02 20:37发布

Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));

After the execution of the above snippet, month gets a value of 10 instead of 11. How come?

标签: java calendar
9条回答
美炸的是我
2楼-- · 2019-01-02 21:19

It would be better to use

Calendar.JANUARY

which is zero ...

查看更多
无与为乐者.
3楼-- · 2019-01-02 21:21

As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.

You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):

int tm_mday;    /* day of month (1 - 31) */
int tm_mon;     /* month of year (0 - 11) */
int tm_year;    /* year - 1900 */

This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 21:23

Months start from zero, like indexes for lists.

Therefore Jan = 0, Feb = 1, etc.

查看更多
登录 后发表回答