This question already has an answer here:
这个问题已经有了答案:
- Java Date getTime function returns negative value 1 answer
- Java Date getTime函数返回负值1答案
I want to calculate the difference between 2 dates with different years, in seconds. I do it like this:
我想计算不同年份的两次约会之间的差异,以秒为单位。我是这样做的:
public static int dateDifference(Date d1, Date d2){
return (int) (d2.getTime() - d1.getTime());
}
The problem is that when I run this for example for these dates:
问题是,当我运行这个例子的时候
d1 = Tue Nov 17 14:18:20 GMT+01:00 2015
d2 = Fri Nov 28 15:37:50 GMT+02:00 2016
I get -169191300
as a result.
结果是-169191300。
But when the years are the same I get the right result, 954959013
.
但当年份相同时,我得到了正确的结果,954959013。
Can someone explain what is happening here?
有人能解释一下这里发生了什么吗?
1 个解决方案
#1
15
use a long
instead of an int
.
用long代替int。
public static long dateDifference(Date d1, Date d2){
return (d2.getTime() - d1.getTime());
}
getTime()
returns a long
because the result can be greater than an integer. When you cast a long greater than Integer.MAX_VALUE
to an integer you get an overflow and the value can turn negative.
getTime()返回一个long,因为结果可能大于一个整数。当你投出一个大于整数的长。MAX_VALUE对一个整数进行溢出,该值可以变为负值。
#1
15
use a long
instead of an int
.
用long代替int。
public static long dateDifference(Date d1, Date d2){
return (d2.getTime() - d1.getTime());
}
getTime()
returns a long
because the result can be greater than an integer. When you cast a long greater than Integer.MAX_VALUE
to an integer you get an overflow and the value can turn negative.
getTime()返回一个long,因为结果可能大于一个整数。当你投出一个大于整数的长。MAX_VALUE对一个整数进行溢出,该值可以变为负值。