i need java code to find difference between two times in 24 hour format for example: 20:00:00 - 04:00:00
and the expected output is 8 hrs but now output is 16 hrs when i tried 12 hour format out put is coming 4.
below is the code used to parse and to find difference
SimpleDateFormat readFormat = new SimpleDateFormat("HH:mm");
Date d1 = readFormat.parse(txtshiftIn);
Date d2 = readFormat.parse(txtshiftOut);
long diff = d2.getTime() - d1.getTime();
input is just 20:00 and 04:00 no seconds and AM/PM part.
The issue with using
Dateis it still expects an actual date even though you are using just the time portion of it, so if you're just sending it the time it will not be correct.Instead use
LocalTimeandChronoUnit.HOURSto get the difference between the time.This will show
-16which means thatlt1is ahead oflt2which indicateslt2is the next day so we can modify it to get the differences as suchThis will give you the
8hour difference you're expecting.UPDATE To account the difference in minutes you can do the following:
This will produce the difference in minutes:
08:30Update 2
Here is a cleaner method that returns a
Duration