This question already has an answer here:
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
In Java, I want to calculate the number of days between two dates.
In my database they are stored as a DATE
datatype, but in my code they are strings.
I want to calculate the no of days between those two strings.
here's a small program which may help you:
In Java 8. You can use instances of
Enum ChronoUnit
to calculate amount of time in different units (days,months, seconds).For Example:
I'm really really REALLY new at Java, so i'm sure that there's an even better way to do what i'm proposing.
I had this same demand and i did it using the difference between the DAYOFYEAR of the two dates. It seemed an easier way to do it...
I can't really evaluate this solution in performance and stability terms, but i think it's ok.
here:
In this case, the output would be (remembering that i'm using the Date Format DD/MM/YYYY):
I know this thread is two years old now, I still don't see a correct answer here.
Unless you want to use Joda or have Java 8 and if you need to subract dates influenced by daylight saving.
So I have written my own solution. The important aspect is that it only works if you really only care about dates because it's necessary to discard the time information, so if you want something like
25.06.2014 - 01.01.2010 = 1636
, this should work regardless of the DST:As the time is always
00:00:00
, using double and thenMath.round()
should help to ignore the missing 60000ms (1 hour) when going from winter to summer time as well as the extra hour if going from summer to winter.This is a small JUnit4 test I use to prove it:
... or if you want to see what it does 'life', replace the assertion with just:
... and this is what the output should look like:
try this code
this function