Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java subtract LocalTime

Tags:

java

localtime

I have two LocalTime objects:

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

How can I found different in minutes between them?

like image 719
Bob Avatar asked Feb 05 '15 20:02

Bob


People also ask

How do you subtract in LocalTime?

The difference between two LocalTime objects can be obtained using the until() method in the LocalTime class in Java. This method requires two parameters i.e. the end time for the LocalTime object and the Temporal unit. Also, it returns the difference between two LocalTime objects in the Temporal unit specified.

How do you subtract time in Java?

String start = "12:00:00"; String end = "02:05:00"; SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); Date date1 = format. parse(start); Date date2 = format. parse(end); long difference = date2. getTime() - date1.

What is LocalTime in Java?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30. 123456789" can be stored in a LocalTime . This class does not store or represent a date or time-zone.


2 Answers

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

like image 80
Yosef Weiner Avatar answered Oct 11 '22 18:10

Yosef Weiner


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

long elapsedMinutes = Duration.between(l1, l2).toMinutes(); 
like image 26
nslxndr Avatar answered Oct 11 '22 19:10

nslxndr