How do I subtract one hour from another as in the example below? (Date not Calendar):
Date date1 = ...
Date date2 = ...
Date dateResult = ...
dateResult = date1 - date2; //(15:00 - 13:30 = 1:30)
...
How do I subtract one hour from another as in the example below? (Date not Calendar):
Date date1 = ...
Date date2 = ...
Date dateResult = ...
dateResult = date1 - date2; //(15:00 - 13:30 = 1:30)
...
Here a working solution (the limitations are described below the code)
// uses a deprecated constructor, so don't do that in production code
// better and more save to use a Calendar instead
Date date1 = new Date(115, 0, 1, 15, 0);
Date date2 = new Date(115, 0, 1, 13, 30);
int millisPerDay = (int) TimeUnit.DAYS.toMillis(1);
int millisPerHour = (int) TimeUnit.HOURS.toMillis(1);
int millisPerMinute = (int) TimeUnit.MINUTES.toMillis(1);
int millisPerSecond = (int) TimeUnit.SECONDS.toMillis(1);
long millisDate1 = date1.getTime();
long millisDate2 = date2.getTime();
long millisDifference = millisDate1 - millisDate2;
int durationDays = (int) millisDifference / millisPerDay;
long remainder = millisDifference - durationDays * millisPerDay;
int durationHours = (int) remainder / millisPerHour;
remainder = remainder - durationHours * millisPerHour;
int durationMinutes = (int) remainder / millisPerMinute;
remainder = remainder - durationMinutes * millisPerMinute;
int durationSeconds = (int) remainder / millisPerSecond;
System.out.printf("%02d:%02d:%02d.%03d%n",
durationDays,
durationHours,
durationMinutes,
durationSeconds
);
What are the limitations:
- first of all, this piece of code is not tested (beside for your given example)
- the example uses a deprecated constructor of Date
(never use that in new code)
- there might be range overflows if the difference between the dates are to big
- the code doesn't know anything about daylight saving times
- the code doesn't know anything about timezones
- the code doesn't know anything about leap seconds
But in following case I would assume it works correct (this needs to be proved by further testing)
- if you are only interested in pure execution duration (both dates would have the same timezone basis and because of it's pure technical aspect the daylight saving might be ignored)
So now it's up to you to decide if you take something from this snippet or better look for another solution.