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!
getDays() + " days " + time[0] + " hours " + time[1] + " minutes " + time[2] + " seconds.");
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With