Net-informations.com
SiteMap  | About    

Difference between two Java date instances

There are many ways you can find the difference between dates. The following is the simplest way to find the difference between two dates. You could just take the number of milliseconds between the two Date objects and divide by the number of milliseconds in 24 hours, with following rules :

That is, dateDifference in milliseconds/(1000 * 60 * 60 * 24) )

  1. This won't take time zones into consideration - Date is always in UTC
  2. This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)

The following Java program calculate the difference between two dates:

Date difference in java 8

It is very difficult to accurately calculate the difference between two dates in Java without using third party library unless you have time to develop your own java library like Joda , which purposefully takes these things into consideration. Thankfully, you don't need to worry because Java 8 got lucky third time. Java 8 made first attempt to upgrade this date/time API.

Example

Daylight Saving Time solution

DST (Daylight Saving Time) is the practice of setting the clocks forward 1 hour from standard time during the summer months, and back again in the fall, in order to make better use of natural daylight. The above solution caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.