我需要在Java中找到两个日期之间的差异,差异应该包括开始日期和结束日期。我尝试使用下面的代码,但不包括开始和结束日期。
long diffDays = Days.daysBetween(new DateTime(startDate), new DateTime(endDate)).getDays();
有没有实用方法可以达到这个目的?
答案 0 :(得分: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