-3

我需要找到 Java 中两个日期之间的差异,并且差异应该包括开始日期和结束日期。我尝试使用下面的代码,但它不包括开始和结束日期。

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

有什么实用方法可以实现这一点吗?

4

1 回答 1

0

如果您不使用库,这将是其中一种方法:

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

或者你可以使用Joda

于 2017-09-11T07:26:18.187 回答