简体   繁体   中英

Android (Java) GregorianCalendar odd behavior

I have problem with java Date type. Why in my code days and days1 both equall 88?

GregorianCalendar dateNow = new GregorianCalendar(2014,03,31);
GregorianCalendar dateFirstDay = new GregorianCalendar(2014,01,01);
long diffInMillies = dateNow. getTimeInMillis() - dateFirstDay. getTimeInMillis();
int days = (int) (diffInMillies / (1000*60*60*24));

GregorianCalendar dateNow1 = new GregorianCalendar(2014,04,01);
GregorianCalendar dateFirstDay1 = new GregorianCalendar(2014,01,01);
long diffInMillies1 = dateNow1. getTimeInMillis() - dateFirstDay1. getTimeInMillis();
int days1 = (int) (diffInMillies1 / (1000*60*60*24));

The reason is that you are giving dateNow a month of 03, which means it is taking it as April, since it starts the month from 0. 0=Jan;1=Feb etc. Now, you are giving day of month as 31. Since April only has 30 days, it is incrementing and treating the date as 1 May, which is same as your dateNow1.

Hence the same values.

Hope this helps.

It's the expected behavior, infact:

GregorianCalendar dateNow = new GregorianCalendar(2014,03,31);

represents the same date as

GregorianCalendar dateNow1 = new GregorianCalendar(2014,04,01);

This is because months count start from 0 , so 03 is April and not March. Visit Official GregorianCalendar JavaDoc for more info on constructors usage and other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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