I just found a bug in a website I’m working on and I corrected it. My problem here is that even if I corrected it I don’t understand what was the issue.
I have two dates (I can’t use GregorianCalendar) and I want to evaluate the distance between these two in days. It’s kind of trivial but my code had a weird behaviour.
For specific dates, for instance: 26/04/2008 and 26/05/2008 the number of days should be exactly 30 but I got -19. For other dates, it worked fine. Here is what I did:
Date dMin = ... // -> 26/04/2008
Date dMax = ... // -> 26/05/2008
System.out.println((dMax.getTime()-dMin.getTime())/(1000*60*60*24)); // prints 30
int i = (int) (dMax.getTime()-dMin.getTime())/(1000*60*60*24); // i = -19
So how did I correct it? I did something like this:
long i = (dMax.getTime()-dMin.getTime())/(1000*60*60*24);
And later on, just before I display it on screen, I would cast it as an integer and it’s working fine.
I’m working with GWT and this calculus is done on the client side (so it’s compiled as javascript).
Is there something I am missing there? I guess yes but I can’t find out what it is.
I think there is a problem with your cast (parentheses), see for example:
So your
int i = (int) (dMax.getTime()-dMin.getTime())/(1000*60*60*24); // i = -19first castsdMax.getTime()-dMin.getTime()to int before dividing – you possibly get an overflow there.