struggling with java.util.date

E

Eric

Any help greatly appreciated!!

I have two java.util.date's and I need to find the difference between them.
I have yet to find a way to compute the difference between two dates...
doesn't seem like this should be a difficult thing.

Specifically:
java.util.date d1;
java.util.date d2;
java.util.date d3;

I would like to do something like this: d3 = d2 - d1;


I hope this is just an easy question that I am just being stupid about and
overlooking.


Thanks in advance for any help with this matter?
 
H

Harald Hein

Eric said:
Any help greatly appreciated!!

I have two java.util.date's and I need to find the difference
between them.

Either use Calendar instead, or convert to milliseconds since 1/1/1970.
BTW, if you have to take DST into account, the calculation is non-
trivial if you do it via milliseconds.
 
A

Anton Spaans

Difference in ...:
long difMillSecs = d2.getTime() - d1.getTime();
double difSecs = (double)difMillSecs / 1000.0;
double difMins = difSecs / 60.0;
double difHours = difMins / 60.0;
double difDays... and now you get into some trouble, because of daylight
saving times. Use Calendar class for this.

Also, when trying to calculate the difference in number of months: leap
years. Use the Calendar (GregorianCalendar) class to do so.

What difference are you looking for (difference in seconds, minutes...)?

Note this statement has no real meaning:

Date d3 = new Date(d2.getTime() - d1.getTime());

Now d3 is the date (day/month/year/time) that is {d2.getTime() -
d1.getTime()} milliseconds from 1-1-1970....
-- Anton.
 
V

VisionSet

Eric said:
Any help greatly appreciated!!

I have two java.util.date's and I need to find the difference between them.
I have yet to find a way to compute the difference between two dates...
doesn't seem like this should be a difficult thing.

Specifically:
java.util.date d1;
java.util.date d2;
java.util.date d3;

I would like to do something like this: d3 = d2 - d1;

Well you can't get a Date by subtracting two Dates, it doesn't make sense;
doing that produces a Duration.

If you use Date.getTime(), which returns a long that is arbitrarily the
milliseconds since 1/1/1970 GMT, and do:

date1.getTime() - date2.getTime();

you will get a duration of type long
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top