IAmYourFaja
IAmYourFaja

Reputation: 56894

Difference of two Joda LocalDateTimes

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!

Upvotes: 10

Views: 14888

Answers (4)

Ilya
Ilya

Reputation: 29693

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)

Upvotes: 20

Irshad
Irshad

Reputation: 1114

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;
}

Upvotes: 1

Cícero Moura
Cícero Moura

Reputation: 2333

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/

Upvotes: 0

kbec
kbec

Reputation: 3465

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));
}

Upvotes: 10

Related Questions