struggling with java.util.date

Discussion in 'Java' started by Eric, Dec 1, 2003.

  1. Eric

    Eric Guest

    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?
     
    Eric, Dec 1, 2003
    #1
    1. Advertisements

  2. Eric

    Harald Hein Guest

    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.
     
    Harald Hein, Dec 1, 2003
    #2
    1. Advertisements

  3. Eric

    Anton Spaans Guest

    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.
     
    Anton Spaans, Dec 2, 2003
    #3
  4. Eric

    VisionSet Guest

    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
     
    VisionSet, Dec 2, 2003
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.