Difference of two Joda LocalDateTimes
I found a workaround by using following steps:
- Take two LocalDateTime objects as Start and End
- Convert both of them to Instant object such as
start.toInstant(ZoneOffset.UTC);
- Calculate the Duration using
Duration.between(instant t1, instant t2)
- 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;
}
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));
}
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)