I was coding a method that gets the number of days between two dates. When I was testing the method I found that sometimes it returns a result that differs with the correct answer in 1 day. I check step by step my method and I found this problem.
I don't know what I am doing wrong, but I don't have idea how to solve it, it is too strange.
---------------------
private int getNumberOfDaysBetween(Date date1, Date date2) {
long fechaInicialMs = date1.getTime();
long fechaFinalMs = date2.getTime();
long dif = fechaFinalMs - fechaInicialMs;
double dias = Math.floor(dif / (1000 * 60 * 60 * 24));
return (int) dias;
}
client:
Date test1 = new Date(2010, 2, 24);
Date test2 = new Date(2010, 2, 25);
System.out.println("Result: " + getNumberOfDaysBetween(test2, test1));
With this input it returns 1 that is ok, but when the input is:
Date test1 = new Date(2010, 2, 27);
Date test2 = new Date(2010, 2, 28);
System.out.println("Result: " + getNumberOfDaysBetween(test2, test1));
With this input it returns 0
Then I checked what the getTime method was bringing and I found that for the date 2010/03/28 (Date test1 = new Date(2010, 2, 27)) it brings
less milliseconds.
Each day has 86400000 milliseconds (1000*24*60*60) but for that specific date the method getTime() counts just 82800000 then for that reason when I use the method floor() in my method it returns 0.
I printed what getTime returns for different dates in order you appreciate the problem:
Date getTime()
Sat Mar 19 00:00:00 EET 3910 61227093600000
Sun Mar 20 00:00:00 EET 3910 61227180000000
Mon Mar 21 00:00:00 EET 3910 61227266400000
Tue Mar 22 00:00:00 EET 3910 61227352800000
Wed Mar 23 00:00:00 EET 3910 61227439200000
Thu Mar 24 00:00:00 EET 3910 61227525600000
Fri Mar 25 00:00:00 EET 3910 61227612000000
Sat Mar 26 00:00:00 EET 3910 61227698400000
Sun Mar 27 00:00:00 EET 3910 61227784800000
Mon Mar 28 00:00:00 EEST 3910 61227867600000
Tue Mar 29 00:00:00 EEST 3910 61227954000000
Wed Mar 30 00:00:00 EEST 3910 61228040400000
Thu Mar 31 00:00:00 EEST 3910 61228126800000
If you check the difference between each day is exactly 86400000 ms, but with
2010/03/28 it doesn't work.
am I wrong? which one is my mistake??
Maybe I am missing something but I don't have idea what
help!!!