简体   繁体   中英

Timer - How do I calculate the difference between two dates using Joda Time?

I want to get the difference between two times P (start time) and Q (end time) using Joda Time. P and Q could be times on different days or even on the same day. I want to get the difference in format HH-MM-SS, where H=hours, M=minutes, S=seconds.

I want to use this functionality in a timer. I assume that no one will use my timer to measure more than 24 hours.

Please guide me to do this.

Take a look at the Joda time FAQ http://joda-time.sourceforge.net/faq.html#datediff

And you can use a PeriodFormatter to get the format of your choice. Try the following sample code.

DateTime dt = new DateTime();
DateTime twoHoursLater = dt.plusHours(2).plusMinutes(10).plusSeconds(5);
Period period = new Period(dt, twoHoursLater);
PeriodFormatter HHMMSSFormater = new PeriodFormatterBuilder()
        .printZeroAlways()
        .minimumPrintedDigits(2)
        .appendHours().appendSeparator("-")
        .appendMinutes().appendSeparator("-")
        .appendSeconds()
        .toFormatter(); // produce thread-safe formatter
System.out.println(HHMMSSFormater.print(period));

I admire the Joda date/time API. It offers some cool functionality and if I needed an immutable calendar or some of the esoteric calendar options it offers, I'd be all over it.

It is still an external API though.

So ... why use it when you don't have to. In the Joda API, the "Instant" is the exact same thing as a Java API "Date" (or pretty close to it). These are both thin wrappers around a long that represents an instant in POSIX EPOCH UTC time (which is the number of milliseconds that have elapsed since 00:00am Jan 1, 1970 UTC.

If you have either two Instants or two Dates, computing the days between them is trivial, and the Joda library is absolutely not needed for this purpose alone:

public double computeDaysBetweenDates(Date earlier, Date later) {
    long diff;

    diff = later.getTime() - earlier.getTime();
    return ((double) diff) / (86400.0 * 1000.0);
}

This assumes that the number of seconds in a day is 86400 ... and this is mostly true.

Once you have a difference as a double, it is trivial to convert the fractional portion of the answer (which is the fraction of one day) into HH:MM:SS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM