Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find difference between two Joda-Time DateTimes in minutes

Tags:

java

jodatime

People also ask

Which object can be used to find the total number of minutes between two datetime objects?

The timedelta class stores the difference between two datetime objects. To find the difference between two dates in form of minutes, the attribute seconds of timedelta object can be used which can be further divided by 60 to convert to minutes.

What is the replacement of Joda-time?

Correct Option: D. In java 8,we are asked to migrate to java. time (JSR-310) which is a core part of the JDK which replaces joda library project.

What is Joda-time?

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.


Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after


This will get you the difference between two DateTime objects in milliseconds:

DateTime d1 = new DateTime();
DateTime d2 = new DateTime();

long diffInMillis = d2.getMillis() - d1.getMillis();

Something like...

Minutes.minutesBetween(getStart(), getEnd()).getMinutes();

DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();

In practice I think this will always give the same result as the answer based on Duration. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years().

In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.