Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of two Joda LocalDateTimes

Tags:

java

jodatime

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!

like image 791
IAmYourFaja Avatar asked Feb 16 '12 19:02

IAmYourFaja


People also ask

What is the difference between two LocalDateTime in Java 8?

getDays() + " days " + time[0] + " hours " + time[1] + " minutes " + time[2] + " seconds.");

What is the difference between LocalDate and LocalDateTime?

LocalDate – represents a date (year, month, day) LocalDateTime – same as LocalDate, but includes time with nanosecond precision. OffsetDateTime – same as LocalDateTime, but with time zone offset.

What is Joda?

Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.

What is the difference between date and LocalDateTime in Java?

For example, the old Date class contains both date and time components but LocalDate is just date, it doesn't have any time part in it like "15-12-2016", which means when you convert Date to LocalDate then time-related information will be lost and when you convert LocalDate to Date, they will be zero.


1 Answers

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)
like image 97
Ilya Avatar answered Sep 28 '22 08:09

Ilya