简体   繁体   English

Android(Java)GregorianCalendar异常行为

[英]Android (Java) GregorianCalendar odd behavior

I have problem with java Date type. 我在使用Java Date类型时遇到问题。 Why in my code days and days1 both equall 88? 为什么在我的代码中daysdays1days1 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. 原因是您给dateNow提供了一个03的月,这意味着它将4月作为它,因为它从0开始。月份= 0; Jan; 1 = Feb等。现在,您给一个月中的一天作为31。由于4月只有30天,因此会将日期递增并将其视为5月1日,与dateDow1相同。

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. 这是因为月份数从0开始,所以03是4月而不是3月。 Visit Official GregorianCalendar JavaDoc for more info on constructors usage and other. 请访问GregorianCalendar JavaDoc官方网站 ,以获取有关构造函数使用及其他方面的更多信息。

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

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