java.util.Calendar (newbie question)

Status
Not open for further replies.

TheBorg

Ars Tribunus Angusticlavius
8,555
Folks,

I think I'm spoiled by other environments and their handling of dates. I have a Java application with two variables of type Calendar. Is there a straightforward way to return the number of days between the two dates (ie, a simple function call) without writing a ton of code? In Visual Basic it's
code:<HR>
Code:
DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

Thanks in advance,

theBorg

P.S.
 
Mike's solution will give you the number of 24 hour periods between the two dates. I believe that if you want to actually have the number of days (ie Jan 21, Jan 22, Jan 23 is 3.. you know what I mean) you actually have to do a little more coding than that.

I use a variation on the DateComparator found here.

If there is an easier way please let me know. I searched all over the Sun Java Tech Search for an answer and came up with that...

gen
 

MikeApp

Ars Centurion
257
Subscriptor
:oops: Doh.

If you do the division first, you should get the day calculated from the start of the UNIX era, with hours/minutes/seconds lopped off by the cast to int. Then do the subtraction.

int days1 = (int) ( c1.getTimeInMillis() / millisecondsInDay );
int days2 = (int) ( c2.getTimeInMillis() / millisecondsInDay );
int diff = days2 - days1;

This should be more efficient than rolling a Calendar object hundreds or thousands of times (unless I've missed something again :eek: )
 
Status
Not open for further replies.