Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two dates with different years [duplicate]

Tags:

java

date

time

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?

like image 603
user3232446 Avatar asked Nov 17 '15 13:11

user3232446


1 Answers

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.

like image 84
Simulant Avatar answered Oct 22 '22 23:10

Simulant