I'm trying to compare a duration to an integer representing minutes (so another duration) in order to find out if it's a longer or shorter time. I'm trying to use compareTo(Duration duration) method but I can't use an int as parameter. How would I transform that int (minutes) into Duration?
- 1what Duration class are you using?Stultuske– Stultuske2021-03-24 18:16:53 +00:00Commented Mar 24, 2021 at 18:16
- java.time.Durationchiagger– chiagger2021-03-24 18:18:21 +00:00Commented Mar 24, 2021 at 18:18
- 1Duration.ofMinutes(minutesInt)Michael Berry– Michael Berry2021-03-24 18:21:07 +00:00Commented Mar 24, 2021 at 18:21
3 Answers
You can create a duration in minutes with the ofMinutes static method. So, as a silly example
int compareDurations(Duration d) { int myMinutes = 5; Duration durationInMinutes = Duration.ofMinutes(myMinutes); return d.compareTo(durationMinutes); } Comments
I always find code involving compareTo() hard to read. Therefore for most purposes I would prefer to do it the other way around: convert your Duration to minutes and compare using plain < or >.
int minutes = 7; Duration dur = Duration.ofMinutes(7).plusSeconds(30); if (minutes > dur.toMinutes()) { System.out.println("The minutes are longer"); } else { System.out.println("The minutes are shorter or the same"); } Output:
The minutes are shorter or the same
If you need to know whether the minutes are strictly shorter, the code will be a bit longer, of course (no joke intended). One way does involve converting the minutes to a Duration in some cases:
if (minutes > dur.toMinutes()) { System.out.println("The minutes are longer"); } else if (Duration.ofMinutes(minutes).equals(dur)) { System.out.println("The minutes are the same"); } else { System.out.println("The minutes are shorter"); } The minutes are shorter
I really wish the Duration class had had methods isLonger() and isShorter() (even though the names just suggested may not be quite clear when it comes to negative durations). Then I would have recommended converting the minutes to a Duration too as in the accepted answer.
Comments
One way, with Duration:
Duration duration = Duration.of(10, ChronoUnit.SECONDS); int seconds = 5; System.out.println(duration.getSeconds() - seconds); Note, that ChronoUnit has a lot of useful constant members, like MINUTES, DAYS, WEEKS, CENTURIES, etc.
Another way, with LocalTime:
LocalTime localTime = LocalTime.of(0, 0, 15); //hh-mm-ss int seconds = 5; System.out.println(localTime.getSecond() - seconds);