I tried to calculate the difference between the two dates, and I noticed one thing. When calculating only days, daylight saving time starts, so the result will be shorter with 1 day.
To get accurate results, you must also consider the value of the clock.
For instance:
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); Date dfrom = format.parse("03-29-2015"); Date dto = format.parse("03-30-2015"); long diff = dto.getTime() - dfrom.getTime(); System.out.println(diff); System.out.println("Days: "+diff / (24 * 60 * 60 * 1000)); System.out.println("Hours: "+diff / (60 * 60 * 1000) % 24);
Output:
82800000 Days: 0 Hours: 23
Does anyone have a better solution?
source share