9

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.

david blaine
  • 5,683
  • 12
  • 46
  • 55

2 Answers2

19

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));
IceMan
  • 1,398
  • 16
  • 35
  • I see that we have to use - org.joda.time.Period.Period(ReadableInstant startInstant, ReadableInstant endInstant) for the example they gave in your link. If you already know how this is to be done, can you show me ? – david blaine Sep 13 '12 at 00:00
  • @davidblaine I have edited my answer to include some sample code. Try it out. – IceMan Sep 13 '12 at 00:25
  • Thanks ! The output is - 2-10-5. how can I make it 02-10-05 ? – david blaine Sep 13 '12 at 18:27
  • Got the idea here - http://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java – david blaine Sep 13 '12 at 18:52
  • @davidblaine - Use [minimumPrintedDigits\(2\)](http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormatterBuilder.html#minimumPrintedDigits(int)). – David Harkness May 06 '13 at 23:12
  • @IceMan, there is a semi-colon after `appendSeconds()` that is unnecessary and prevents the code from compiling. Can't edit because edits need to be at least 6 characters – ryvantage Nov 12 '15 at 20:40
  • 1
    @ryvantage It looks like an edit to my original answer caused the issue. Its should be fixed now. – IceMan Nov 12 '15 at 20:44
1

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.

scottb
  • 9,908
  • 3
  • 40
  • 56
  • 1
    It has to do with readability. Most people don't see 86400 and instantly think number of seconds in a day. Also, since java.util.Date is mutable it can cause headaches and bugs to the point that people would rather go to a third party API. The response above from @IceMan only had about 3 lines of code to accomplish what he was wanting and the rest was for formatting and that code is much easier for anyone to discern what the intent was. – dsingleton Sep 11 '13 at 16:15
  • 1
    @dsingleton: Readability is important, but I don't see why the intent of the method I provided should be obscure. For example, one could include `private final double MILLIS_IN_A_DAY = 86400.0 * 1000.0` to make the calculation in the final line more clear. And, while it is true that Date is mutable, the above routine is threadsafe ... and this routine could easily be modified to use `longs` directly. The point here is that a simple solution to this problem is accessible without the need for Joda (it does not speak to the broader implications of the Java Date/Time API). – scottb Sep 11 '13 at 17:04