I\'ve got 2 Joda LocalDateTime
objects and need to produce a 3rd that represents the difference between them:
LocalDateTime start = getStartLoca
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)
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));
}
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/
I found a workaround by using following steps:
start.toInstant(ZoneOffset.UTC);
Duration.between(instant t1, instant t2)
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;
}