I have found how to get the hours between two dates and the minutes . What I want is the exact difference between both of them, this is the code that I'm using:
private String getHours(Message punch) {
LocalTime out = Instant.ofEpochMilli(message.getOut().getTime()).atZone(ZoneId.of(message.getTimezone()))
.toLocalTime();
LocalTime in = Instant.ofEpochMilli(message.getIn().getTime()).atZone(ZoneId.of(message.getTimezone()))
.toLocalTime();
Duration duration = Duration.between(in, out);
Long hours = duration.toHours();
Long minutes = duration.toMinutes() - (hours * Constants.MINUTES_IN_AN_HOUR);
return String.format("%d:%d", hours, minutes);
}
It works fine for the major of the cases but I'm having an error in the following case:
Both are the same day, the difference that I'm expecting is 9:01, but I'm getting -14:-59
Debugging the code I realize that out is getting 04:00 and in is getting 18:59.
For almost all the cases it works well but It happens in some scenarios.
I believe your problem is that you are using LocalTime class but you should be using LocalDateTime class. It apears that your timezone is GMT+6, so in your example your in time and out time fall in different days - your in time in the evening of a previous day and out time on the morning of the next day. But because you are using LocalTime you are loosing the fact that those are times in different days. Change your LocalTime to LocalDateTime and see if this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With