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.
But when the years are the same I get the right result, 954959013
.
Can someone explain what is happening here?
use a long
instead of an 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With