# Thread: calculate date difference in days

1. ## calculate date difference in days

Is there a method to calculate de difference in days between two dates?

When the first date is 1 June 23h and the second date is 2 June 1h it must return 1
When the first date is 1 June 1h and the second date is 1 June 3h it must return 0

2. ## Re: calculate date difference in days

Try this...

Code:
```private static final long DAY = 86400000;

public static int daysBetween(Date first, Date second) {
int days = (int) ((first.getTime() / DAY) - (second.getTime() / DAY));
return days < 0 ? -days : days;
}```
Graham.

3. ## Re: calculate date difference in days

Originally Posted by grahamhughes
Try this...

Code:
```private static final long DAY = 86400000;

public static int daysBetween(Date first, Date second) {
int days = (int) ((first.getTime() / DAY) - (second.getTime() / DAY));
return days < 0 ? -days : days;
}```
Graham.
isn't this the same like this: (simple math)
int days = (int) ((first.getTime()-second.getTime()) / DAY);

But in my first example the time between second and first is only 2 hours and this will after rounding result in zero.
In both my two examples the difference in time between second and first is 2 hours, but the first is 1 day and the second is zero days difference.
So I think I gonna need another principle than just look to the subtraction to determine the difference in days between both.

I want to check with this function if a given date is today, tomorrow or the day after tomorrow or ...

4. ## Re: calculate date difference in days

No, it's not the same. Did you try it?

Graham.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•