Search code examples
javadurationlocaltime

Java Duration error from a day to another


I found a very simple problem using Java Duration.

     LocalTime SaturdayStart = LocalTime.of(22, 30); 
     LocalTime SaturdayEnd = LocalTime.of(01, 00);
     System.out.println(SaturdayStart);
     System.out.println(SaturdayEnd);
     System.out.println(Duration.between(SaturdayStart, SaturdayEnd));

The output from this code is:

22:30
01:00
PT-21H-30M

And this is the problem. Instead of 21H, I wanted the duration to be 2H-30M. What is causing the method to be unable to see the "day change" between the two times?


Solution

  • Remember that LocalTime just represents a single time, in one day, without a time zone.

    Since it represents the time you see on the clock in one day, you can't use it to calculate differences between 22:30 today and 01:00 the next day. Your two LocalTime object represent 22:30 today, and 01:00 today respectively.

    To take the day into account, you need a LocalDateTime. This represents not only a time (without a time zone), but also the date in the ISO-8601 calendar system. You can create the two LocalDateTime objects like this:

    LocalDateTime start = LocalDateTime.of(LocalDate.now(), LocalTime.of(22, 30));
    LocalDateTime end = start.plusDays(1).withHour(1).withMinute(0);
    

    And then you can get the duration:

    Duration d = Duration.between(start, end);
    System.out.println(d);
    

    By the way, the - characters you get in your wrong output are not delimiters for different components. They are negative signs. This is because you are subtracting 22:30 from 01:00, which is like subtracting a bigger number from a smaller number, you get a negative number.