Java - Time difference in minutes

后端 未结 4 1145
不思量自难忘°
不思量自难忘° 2021-01-21 11:12

I have this problem with calculating time difference in minutes. Its working fine with exampples like calculating the difference between 2045 and 2300.

But when I want t

4条回答
  •  后悔当初
    2021-01-21 11:53

    Consider using LocalDate, LocalDateTime, LocalTime ZonedDateTime classes from java.time.* package introduced in Java 8. They are very handy in use as they can address various corner cases (e.g. measuring minutes across different time zones, or during autumn and spring time change).

    The thing to you need to know when you calculate time difference is that:

    • LocalTime contains time only
    • LocalDate contains date only (no time)
    • LocalDateTime contains both (date + time.)
    • ZonedDateTime contains date + time + timezone

    This implies that difference between times will be different when you compare with:

    • LocalTime you can diff only time so 20:45 and 23:30 gives 2:45 of difference
    • LocalDate you cannot calculate any time diffs (contains no time)
    • LocalDateTime you can specify date and time, e.g.: 20:45 on 1Jan and 23:30 on 3Jan . Time difference will be 2:45 and 2 days of difference, or 50:45.
    • ZonedDateTime - same as LocalDateTime plus you takes into account DayLightSavings, so if the clock is changed overnight - it will get reflected.

    Here is a snippet for a LocalDateTime:

        LocalDateTime today2045    = LocalDateTime.of(
                LocalDate.now(),
                LocalTime.parse("20:45"));
        LocalDateTime tomorrow0230 = LocalDateTime.of(
                LocalDate.now().plusDays(1),
                LocalTime.parse("02:30"));
    
        System.out.println("Difference [minutes]: " + 
                Duration.between(today2045, tomorrow0230).toMinutes());
    

    For ZonedDateTime taking into account spring/autumn clock changes:

        ZonedDateTime today2045    = ZonedDateTime.of(
                LocalDate.now(),
                LocalTime.parse("20:45"),
                ZoneId.systemDefault());
        ZonedDateTime tomorrow0230 = ZonedDateTime.of(
                LocalDate.now().plusDays(1),
                LocalTime.parse("02:30"),
                ZoneId.systemDefault());
    
        System.out.println("Difference [minutes]: " + 
                Duration.between(today2045, tomorrow0230).toMinutes());
    

    Some info on constructors can be found in Oracle's tutorial here.

提交回复
热议问题