Java subtract LocalTime

前端 未结 4 897
死守一世寂寞
死守一世寂寞 2020-12-03 16:43

I have two LocalTime objects:

LocalTime l1 = LocalTime.parse(\"02:53:40\");
LocalTime l2 = LocalTime.parse(\"02:54:27\");

How

相关标签:
4条回答
  • 2020-12-03 17:06

    I do this with ChronoUnit

    long minutesBetween = ChronoUnit.MINUTES.between(l1,l2);
    

    Example

        LocalTime localTime=LocalTime.now();
        LocalTime localTimeAfter5Minutes=LocalTime.now().plusMinutes(5);
        Long minutesBetween=ChronoUnit.MINUTES.between(localTime,localTimeAfter5Minutes);
        System.out.println("Diffrence between time in munutes : "+minutesBetween);
    

    Output

    Diffrence between time in munutes : 5
    
    0 讨论(0)
  • 2020-12-03 17:15

    You could do this:

    long dif = Math.abs (l1.getLocalMillis () - l2.getLocalMillis ());
    TimeUnit.MINUTES.convert (dif, TimeUnit.MILLISECONDS);
    
    0 讨论(0)
  • 2020-12-03 17:18

    Use until or between, as described by the api

    import java.time.LocalTime;
    import static java.time.temporal.ChronoUnit.MINUTES;
    
    public class SO {
        public static void main(String[] args) {
            LocalTime l1 = LocalTime.parse("02:53:40");
            LocalTime l2 = LocalTime.parse("02:54:27");
            System.out.println(l1.until(l2, MINUTES));
            System.out.println(MINUTES.between(l1, l2));
        }
    }
    

    0
    0

    0 讨论(0)
  • 2020-12-03 17:19

    Since Java 8 you can use Duration class. I think that gives the most elegant solution:

    long elapsedMinutes = Duration.between(l1, l2).toMinutes();
    
    0 讨论(0)
提交回复
热议问题