Sep 13

## How to calculate the difference between two Date’s or times

Problem is you have two Date instances and you want to get the elapsed time between them.

Getting the number of seconds is easy, you can just take the difference of value returned by the getTime() method.

```   long elapsed = end.getTime() - start.getTime();
```

But what if you want to know how many days, hours and minutes have elapsed.

One method is to do the calculations yourself

```   final long ONE_SECOND = 1000;
final long ONE_MINUTE = ONE_SECOND * 60;
final long ONE_HOUR = ONE_MINUTE * 60;
final long ONE_DAY = ONE_HOUR * 24;
long days = elapsed / ONE_DAY;
elapsed %= ONE_DAY;
long hours = elapsed / ONE_HOUR;
elapsed %= ONE_HOUR;
long minutes = elapsed / ONE_MINUTE;
elapsed %= ONE_MINUTE;
long seconds = elapsed / ONE_SECOND;
```

Or alternatively if you are just interested in the numbers of hours, minutes and seconds where the elapsed period is less than 24 hours then you can use the date/time handling classes provided by Java

```DateFormat dateFormat =
new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
Calendar cal = Calendar.getInstance();
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTime(new Date(elapsed));
System.out.println(dateFormat.format(cal.getTime()));
```

NB. The second method can actually be adapted to get the number of days as well if required.

written by objects \\ tags: , , , ,