Find the difference between two dates (Inclusive of start and end date) in Java

1.8k views Asked by At

I need to find the difference between two dates in Java and the difference should be inclusive of start and end date. I tried using below piece of code but it is not including start and end date.

long diffDays = Days.daysBetween(new DateTime(startDate), new DateTime(endDate)).getDays();

Is there any utility method to achieve this?

1

There are 1 answers

2
FreedomPride On

If you're not using a library this would be one of the method:

public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
    long diffInMillies = date2.getTime() - date1.getTime();
    List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
    Collections.reverse(units);
    Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
    long milliesRest = diffInMillies;
    for ( TimeUnit unit : units ) {
        long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
        long diffInMilliesForUnit = unit.toMillis(diff);
        milliesRest = milliesRest - diffInMilliesForUnit;
        result.put(unit,diff);
    }
    return result;
}

Or else you could use Joda