10

I've got 2 Joda LocalDateTime objects and need to produce a 3rd that represents the difference between them:

LocalDateTime start = getStartLocalDateTime();
LocalDateTime end = getEndLocalDateTime();

LocalDateTime diff = ???

The only way I can figure is to painstakingly go through each date/time field and performs its respective minus operation:

LocalDateTime diff = end;

diff.minusYears(start.getYear());
diff.minusMonths(start.getMonthOfYear());
diff.minusDays(start.getDayOfMonth());
diff.minusHours(start.getHourOfDay());
diff.minusMinutes(start.getMinuteOfHour());
diff.minusSeconds(start.getSecondsOfMinute());

The end result would simply be to call diff's toString() method and get something meaningful. For instance if start.toString() produces 2012/02/08T15:05:00, and end.toString() produces 2012/02/08T16:00:00, then diff.toString() would be the difference (55 minutes) and might look like 2012/02/08T00:55:00.

And, if this is a terrible abuse of LocalDateTime, then I just need to know how to take the time difference between the two and put that difference into an easy-to-read (human friendly) format.

Thanks in advance!

IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

4 Answers4

20

You can use org.joda.time.Period class for this - in particular the fieldDifference method.

Example:

LocalDateTime endOfMonth = now.dayOfMonth().withMaximumValue();
LocalDateTime firstOfMonth = now.dayOfMonth().withMinimumValue();
Period period = Period.fieldDifference(firstOfMonth, endOfMonth)
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Ilya
  • 29,135
  • 19
  • 110
  • 158
  • 6
    I like Joda, but I am always overwhelmed. `Period` and `Duration`, sounds alike, but is quite different. I see the need, but it’s not always intuitive. – Michael Piefel Apr 30 '12 at 08:27
  • @MPi: Agreed. What's a `ReadablePartial`? Why do I need it to see whether a `LocalDateTime` was a certain amount of time ago? Agh! – william.berg Feb 05 '13 at 12:50
  • Because Period could be a undefined absolute time. For instance, the Period between 14:35 and 15:36, which is a PartialReadable "time of day", will always be 1 hour and 1 minute. – Niclas Hedhman May 19 '13 at 01:52
  • The point is that a Period accounts for such things as daylight savings time; a Period between two times may not always be what it seems that it should be, depending on the start/end datetimes chosen. A Duration is simpler, it will always be a fixed exact amount of time. – Ed Randall May 21 '13 at 12:23
  • 2
    [API Doc for Period](http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html) – reto Jul 11 '13 at 09:02
10

Duration is better for some cases. You can get a "timezone-independent" duration for use with LocalDateTimes (in local time line) by this trick:

public static Duration getLocalDuration(LocalDateTime start, LocalDateTime end) {
    return new Duration(start.toDateTime(DateTimeZone.UTC), end.toDateTime(DateTimeZone.UTC));
}
kbec
  • 3,415
  • 3
  • 27
  • 42
1

I found a workaround by using following steps:

  1. Take two LocalDateTime objects as Start and End
  2. Convert both of them to Instant object such as start.toInstant(ZoneOffset.UTC);
  3. Calculate the Duration using Duration.between(instant t1, instant t2)
  4. Convert it into nanoseconds or milliseconds or seconds using various conversion methods. Nanoseconds can be calculated as Duration.toNanos()

I have provided a full example below.

public long getDuration(LocalDateTime start, LocalDateTime end) {

    //convert the LocalDateTime Object to an Instant 
    Instant startInstant = start.toInstant(ZoneOffset.UTC);         
    Instant endInstant   =   end.toInstant(ZoneOffset.UTC);

    //difference between two Instants is calculated
    //convert to nano seconds or milliseconds 
    long duration=Duration.between(startInstant, endInstant).toNanos();

    return duration;
}
MikeMB
  • 20,029
  • 9
  • 57
  • 102
Irshad
  • 1,016
  • 11
  • 30
0
public static void printTimeDiffJoda(final String start, final String end) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            // Parse datetime string to org.joda.time.DateTime instance
            DateTime startDate = new DateTime(format.parse(start));
            DateTime endDate = new DateTime(format.parse(end));

            System.out.println("Joda Time API - Time Difference ");
            System.out.println("in years: " + Years.yearsBetween(startDate, endDate).getYears());
            System.out.println("in months: " + Months.monthsBetween(startDate, endDate).getMonths());
            System.out.println("in days: " + Days.daysBetween(startDate, endDate).getDays());
            System.out.println("in hours: " + Hours.hoursBetween(startDate, endDate).getHours());
            System.out.println("in minutes: " + Minutes.minutesBetween(startDate, endDate).getMinutes());
            System.out.println("in seconds: " + Seconds.secondsBetween(startDate, endDate).getSeconds());
            System.out.println();

        } catch (ParseException e) {
            e.printStackTrace();
        }
}

By http://www.luyue.org/calculate-difference-between-two-dates/

Cícero Moura
  • 2,027
  • 1
  • 24
  • 36