-3

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?

Vijay
  • 19
  • 1
  • 5
  • 2
    Please add an [mcve]. (Which includes example data with expected outcome). – Fildor Sep 11 '17 at 07:25
  • What library are you using that `Days` and `DateTime` come from? Joda-Time?? – Ole V.V. Sep 11 '17 at 07:49
  • 1
    If the problem is it doesn’t include both start and end date, can’t you just add 1 (or 2 if necessary)? – Ole V.V. Sep 11 '17 at 07:50
  • 1
    The utility method I would use, is `ChronoUnit.DAYS.between()`. It doesn’t include both start and end date either, so we would need to add 1. – Ole V.V. Sep 11 '17 at 07:52

1 Answers1

0

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

FreedomPride
  • 1,098
  • 1
  • 7
  • 30
  • 1
    Joda-Time is a better suggestion, still not the best one. “Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to `java.time` (JSR-310).“ Quoted from [the Joda-Time homepage](http://www.joda.org/joda-time/). – Ole V.V. Sep 11 '17 at 07:45
  • 1
    In any case, please don’t teach the young ones the long outdated `Date` class. As both you and I have mentioned, today we have so much better. If not using Java 8 (or later) yet, i would still think [the **ThreeTen Backport**](http://www.threeten.org/threetenbp/) is better than Joda-Time. – Ole V.V. Sep 11 '17 at 07:45