I am trying to covert the exact amount of time between two Calendar objects in Java.
This is the code that I currently have...
public static Map<TimeUnit, Long> computeDifference(Calendar date1, Calendar date2) {
long diffInMillies = date2.getTimeInMillis() - date1.getTimeInMillis();
//create the list
List<TimeUnit> units = new ArrayList<TimeUnit>();
units.add(TimeUnit.SECONDS);
units.add(TimeUnit.MINUTES);
units.add(TimeUnit.HOURS);
units.add(TimeUnit.DAYS);
Collections.reverse(units);
//create the result map of TimeUnit and difference
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
//calculate difference in millisecond
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
//put the result in the map
result.put(unit,diff);
}
return result;
}
When printed, the output looks like this {DAYS=1, HOURS=10, MINUTES=30, SECONDS=45}
for input date1 = 19 August 2019 02:00:00
and date2 = 20 August 2019 12:30:45
The largest time unit available in this method is DAYS
, but I want to find something that includes both months and years. I realize that TimeUnit doesn't really have anything to do with specific calendar dates (rather a 24-hour interval), which is why I was wondering if there is any way to make this conversion using the Calendar class or something similar. I've also looked into ChronoUnit as a substitute for TimeUnit, but that won't work for the same reason TimeUnit doesn't.
Would love any suggestions for how to incorporate larger time units. Thank you!