Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two JodaTime LocalTime stamps?

I am using JodaTime LocalTime in order to specify times. How can I get the difference in minutes between two times?

LocalTime startT = new LocalTime(6,30);
LocalTime endT = new LocalTime(12,15);

// LocalTime duration = this.endT.minusMinutes(startT);
// int durationMinutes = duration.getMinutes();
like image 937
Klausos Klausos Avatar asked Mar 13 '14 09:03

Klausos Klausos


2 Answers

If you ask

How can I get the difference in minutes between two times?

then I would think of following more intuitive solution:

LocalTime startT = new LocalTime(6,30);
LocalTime endT = new LocalTime(12,15);
int minutes = Minutes.minutesBetween(startT, endT).getMinutes(); // 345m = 6h - 15m

The expression

Period.fieldDifference(startT, endT).getMinutes()

will only yield -15 that means not taking in account the hour difference and hence not converting the hours to minutes. If the second expression is really what you want then the question should rather be like:

How can I get the difference between the minute-parts of two LocalTime-instances?

Updated for Java-8:

LocalTime startT = LocalTime.of(6,30);
LocalTime endT = LocalTime.of(12,15);

long minutes = ChronoUnit.MINUTES.between(startT, endT);

System.out.println(minutes); // output: 345

// Answer to a recommendation in a comment:
// Attention JSR-310 has no typesafety regarding units (a bad design choice)
// => UnsupportedTemporalTypeException: Unsupported unit: Minutes
minutes = Duration.between(startT, endT).get(ChronoUnit.MINUTES);
like image 92
Meno Hochschild Avatar answered Oct 06 '22 00:10

Meno Hochschild


If I understood your question properly the following should do the job:

Period diff = Period.fieldDifference(startT, endT);
int minutes = diff.getMinutes();  
like image 41
Anto Avatar answered Oct 05 '22 23:10

Anto