Number of days between two dates in Java

---
update (23.1.2007): please don't use the code below. You should use this library instead. It's not perfect as the API is ... well Javaish, but it works fine and has a simple class for the task that I was trying to accomplish below.
---

Java has no (as far as I know) TimeSpan class, so you have to calculate this on your own.
Now the first thought would be to do something like: date1.getTime - date2.getTime / milliseconds in a day.
But this returns wrong results as there are some rounding issues.
The correct way to get number of days between two days is this:

Calendar endDate = Calendar.getInstance();
endDate.setTime ( SET_YOUR_TIME_HERE );
Calendar startDate = Calendar.getInstance();
startDate.setTime ( SET_YOUR_TIME_HERE );

int days = endDate .get(Calendar.DAY_OF_YEAR) - startDate .get(Calendar.DAY_OF_YEAR);
Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.