开发者

About GregorianCalendar : the same input but different output in java

开发者 https://www.devze.com 2023-02-04 15:58 出处:网络
I want to use milliseconds to set a new date in my program,but it doesnt work. Is there anybody can tell me why it doesnt work?

I want to use milliseconds to set a new date in my program,but it doesnt work. Is there anybody can tell me why it doesnt work?

Calendar r_1 = new GregorianCalendar(2011,0,1);

r_1.add(Calendar.DAY_OF_MONTH,2);

System.out.println(r_1.getTime());

long date_1 = r_1.getTimeInMillis() + 2*24*60*60*1000;

r_1.setTimeInMillis(startTime1);

System.out.println(r_1.getTime());

It works both very correct , but if i change the day from 2 to 25,then it doenst work .

----------the output is correct ,it is 2011/01/26 ----------

Calendar r_1 = new GregorianCalendar(2011,0,1);

r_1.add(Calendar.DAY_OF_MONTH,25);

System.out.println(r_1.getTime());

-----------the output is incorrect now ,it is 2010/12/07------

long date_1 = r_1.getTimeInMillis() + 25*24*60*60*1000;//i have change 2 to 25

r_1.setTimeInMillis(startTime1);

System.out.println(r_1.getTime());

T开发者_StackOverflow中文版hanks


The expression 25*24*60*60*1000 is an integer, and you have overflowed the size of an integer, creating a negative number.

Your expression is 2,160,000,000 milliseconds. The largest value an int can hold is 2,147,483,647.

To fix this, you have to force the expression to be a long, as follows

25L*24*60*60*1000


25*24*60*60*1000 is too large to fit in an int. Try 25L*24*60*60*1000 which is a long constant.


Try something like that:

final long k = 25*24*60*60*1000L;
long date_1 = r_1.getTimeInMillis() + k;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号