Find total hours between two Dates

前端 未结 11 1364
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    2020-11-28 06:51

    java.time.Duration

    I should like to contribute the modern (java 8+) answer. The solutions using Joda-Time are fine. The Joda-Time project is in maintenance mode, so for new code we should not use it. I follow the official recommendation from the Joda-Time project and use java.time, the modern Java date and time API:

        Duration dur = Duration.between(startDate, endDate);
        String result = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
        System.out.println(result);
    

    This works if startDate and endDate both have type Instant or OffsetDateTime or ZonedDateTime or LocalDateTime or LocalTime. All of the mentioned types are from java.time package. If starting with LocalDate, call either of the atStartOfDay methods.

    The toMinutesPart methof was introduced in Java 9. If you are using Java 8 (ot ThreeTen Backport), search for java format duration or similar to learn how to format the duration into hours and minutes.

    Two quotes from the Joda-Time home page:

    Users are now asked to migrate to java.time (JSR-310).

    Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

    Links

    • Oracle tutorial: Date Time explaining how to use java.time.
    • Joda-Time home page

提交回复
热议问题