Sateesh Sateesh - 4 months ago 8
Java Question

Need number of days based on difference of two dates

Scenario:


My result = Report generation date - Visited date


Example:


Report generation date is : 20/07/2016


If Visited date is 19/07/2016 - result is 0, if Visited date is 18/07/2016 - result is 1, if Visited date is 17/07/2016 - result is 2, etc.

Answer

Try This

 public static void main(String []args) {
    System.out.println(System.currentTimeMillis());
    System.out.println(new Date());
    Map<TimeUnit,Long> result = computeDiff(
            new Date("7/20/2016"),
        new Date("8/20/2016")
    );
    System.out.println(result);
 }

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;
}

}

Comments