Search code examples
javadatetimecalendar

Simple date class in Java


Is there a date class in Java which I can construct with a year, month, day, hour, minute, second and millisecond and then do comparisons which give the number of milliseonds between two date values, ignoring things like daylight saving, leap seconds etc? Can I use the Calendar class for this? I was thinking about doing that, but it talks about leap seconds and daylight saving, and I don't want that to affect the calculations.

It is important that the following invariant holds true all the times:

For all y1, y2, m1, m2, d1, d2, h, m, s, ms:

(
    f(y1, m1, d1, h, m, s, ms).getTimeInMillis() - 
    f(y2, m2, d2, h, m, s, ms).getTimeInMillis()
) 
% 
(24 * 60 * 60 * 1000) == 0

I basically need to know what the function f should be.


Solution

  • I would try using Joda DateTime where you could do

    DateTime d1 = new DateTime(y1,m1,d1,h1,m1,s1,ms1);
    DateTime d2 = new DateTime(y2,m2,d2,h2,m2,s2,ms2);
    long delta = d1.toMillis() - d2.toMillis();
    

    Also consider:

     DateTime d1 = new DateTime(y1,m1,d1,h1,m1,s1,ms1);
     DateTime d2 = new DateTime(y2,m2,d2,h2,m2,s2,ms2);
     Duration delta = new Duration( d1, d2);
     int days = delta.toPeriod().getDays();
    

    If you have unusual needs you may want to look at Joda Chronology objects.