Find total hours between two Dates

前端 未结 11 1340
抹茶落季
抹茶落季 2020-11-28 06:00

I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like w

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 06:35

    Here's a pure Java 8+ solution that does not involve Joda or mathematical operations

    import java.time.*;
    import java.time.temporal.*;
    
    // given two java.util.Dates
    Date startDate ...
    Date endDate ...
    
    // convert them to ZonedDateTime instances
    ZonedDateTime start = ZonedDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault());
    ZonedDateTime end = ZonedDateTime.ofInstant(endDate.toInstant(), ZoneId.systemDefault());
    
    // get the total duration of minutes between them
    Duration total = Duration.ofMinutes(ChronoUnit.MINUTES.between(start, end));
    
    // use the duration to determine the hours and minutes values
    long hours = total.toHours();
    long minutes = total.minusHours(hours).toMinutes();
    

提交回复
热议问题