How to calculate time difference in java?

后端 未结 17 1525
醉酒成梦
醉酒成梦 2020-11-22 16:33

I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.

17条回答
  •  没有蜡笔的小新
    2020-11-22 17:02

    Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.

    Advanced Java 8 libraries. ChronoUnit for Differences.

    ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.

    LocalTime one = LocalTime.of(5,15);
    LocalTime two = LocalTime.of(6,30);
    LocalDate date = LocalDate.of(2019, 1, 29);
    
    System.out.println(ChronoUnit.HOURS.between(one, two)); //1
    System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
    System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
    

    First example shows that between truncates rather than rounds.

    The second shows how easy it is to count different units.

    And the last example reminds us that we should not mess up with dates and times in Java :)

提交回复
热议问题