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

Below is the method I wrote:

public List<Map<String, Object>> loadNotYetInEmployee(int shift, Date date,
        int transitionVal, String type, User user) {

    DateTime datetime = new DateTime(date);
    datetime = datetime
            .plus(Period.minutes(shiftTiming.getSession1InTime()));

    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    sql = SqlMapUtils.getSql("attendance.attendancestatus.latein",
            parameters);
    result = getJdbcTemplate().queryForList(sql);
    for (int i = 0; i < result.size(); i++) {
        Date punchInTime = (Date) result.get(i).get("punchtime");
        DateTime punchTime = new DateTime(punchInTime);
    }
    return result;
}

Now from my method you can see I have a Joda-Time DateTime object in object named datetime and from my result I am getting one timestamp which I am converting to jodatime punchTime. Now I want to find out the diff between these two dates, how do I do that?

This question is related to java jodatime

The answer is


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();

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.


Something like...

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

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