Reputation: 457
I am trying to calculate the number of days between two dates.
First case :
String string = "01/03/2014";
Date dateFin = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
string = "31/03/2014";
Date dateDebut = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
long result = Math.abs(dateFin.getTime() - dateDebut.getTime());
System.out.println((int) (result / (long) (1000 * 3600 * 24)));
=> Result :
29
Second case :
String string = "01/03/2013";
Date dateFin = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
string = "31/03/2013";
Date dateDebut = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).parse(string);
long result = Math.abs(dateFin.getTime() - dateDebut.getTime());
System.out.println((int) (result / (long) (1000 * 3600 * 24)));
=> Result :
30
Question:
Why there is a difference between this two cases?
Thanks
Upvotes: 2
Views: 135
Reputation: 39477
The value in result
is one hour less than the exact 24*30
hours. If you add 3600000
(that is 1 hour) to result
, you will get the exact 24
hours (expressed in milliseconds). Apparently in France they change clocks from Winter to Summer time in the month of March. So in March there are 24*30 - 1
hours, not 24
hours. This explains why you don't have the same problem when you try the two May dates. This is my best explanation based on what I'm seeing.
See also:
http://timeanddate.com/time/change/france/paris?year=2013
http://timeanddate.com/time/change/france/paris?year=2014
You are parsing 31/03/2013 (i.e. 00:00 AM). The clock change didn't happen
until 31/03/2013, 02:00 AM. So in 2013 you have the exact 30*24 hours in March,
while in 2014 you have 1 hour less as the change happened on 3/30/2014.
Upvotes: 3