Reputation: 16050
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();
Upvotes: 9
Views: 9423
Reputation: 44061
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?
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);
Upvotes: 17
Reputation: 4305
If I understood your question properly the following should do the job:
Period diff = Period.fieldDifference(startT, endT);
int minutes = diff.getMinutes();
Upvotes: 2