chiagger
chiagger

Reputation: 73

How can I turn an int (minutes) into a Duration in java?

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?

Upvotes: 2

Views: 14455

Answers (3)

Anonymous
Anonymous

Reputation: 86399

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.

Upvotes: 3

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11136

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);

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27159

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);
}

Upvotes: 7

Related Questions