Java Data Type How to - Calculate elapsed time

Question

We would like to know how to calculate elapsed time.

Answer

```import java.util.Calendar;
//from  ww w. j ava  2 s  .  com
public class Main {
public static void main(String[] args) throws Exception {
Calendar start = Calendar.getInstance();
start.set(2015, 1, 21, 11, 1, 11);
Calendar end = Calendar.getInstance();

Calendar clone = (Calendar) start.clone();
int year = elapsed(clone, end, Calendar.YEAR);
System.out.println(year+" year");
clone.add(Calendar.YEAR, year);
int month = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, month);
System.out.println(month+" month");

int date = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, date);
System.out.println(date+" day");

int hour = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, hour);
System.out.println(hour+" hour");

int minute = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, minute);
System.out.println(minute+" minute");

int millis = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
System.out.println(millis+" millis");

}

private static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone();
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}

}
```

The code above generates the following result.