2

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

user3489875
  • 457
  • 4
  • 10

1 Answers1

3

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.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • so why for year 2013 it ok but not for year 2014? – user3489875 Nov 05 '14 at 16:54
  • Well, since both the cases are in March, the daylight saving should be equal in both years, no? – Narmer Nov 05 '14 at 16:54
  • @Narmer Are you sure in both years the change happened in March? Check these two and think some more. http://www.timeanddate.com/time/change/france/paris?year=2013 http://www.timeanddate.com/time/change/france/paris?year=2014 You will see why the result differs. – peter.petrov Nov 05 '14 at 16:55
  • Nope, that's what I'm searching... Usually (at least in Italy) we tend to apply the daylight saving always in the same month and on sunday, to ease the change. – Narmer Nov 05 '14 at 16:57
  • @Narmer He's parsing 31/03/2013. The change didn't happen until 31/03/2013, 02:00 AM. So in 2013 he has the exact 30*24 hours, while in 2014 he has 1 hour less as the change happened on 3/30/2014. – peter.petrov Nov 05 '14 at 16:58
  • Right, just a matter of hours :) – Narmer Nov 05 '14 at 17:00