Why does the Duration class not have 'toSeconds()' method?

JavaJava 8Api DesignJava Time

Java Problem Overview


I was looking at the Duration class in Java 8 and noticed that it does not have:

long toSeconds();

But it has all other toXXXXX() to get days, hours, minutes, millis, nanos. I do see a getSeconds() method that returns the number of seconds within this duration object. There is also a get(TemporalUnit unit) method to get the duration as the requested time unit. But why not keep the toSeconds() method for consistency?

Java Solutions


Solution 1 - Java

Let's look at what the docs say:

> This class models a quantity or amount of time in terms of seconds and nanoseconds.

That basically means that the unit used to store the amount of time represented is seconds. For example, to store the duration 5 minutes and 10 nanoseconds, 300 (seconds) and 10 (nanoseconds) are stored. Because of this, there is no need to convert to seconds. You get the seconds using getSeconds().

See what I mean here? All the other methods convert to the corresponding units: days, minutes, hours... That's why they start with to, meaning convertedTo. Since you don't need to do a conversion to get the duration in seconds, the method that returns the duration in seconds starts with get.

Solution 2 - Java

This is a known issue whose fix is scheduled for Java 9: https://bugs.openjdk.java.net/browse/JDK-8142936

New method added in Java 9, toSeconds. See source code.

/**
 * Gets the number of seconds in this duration.
 * <p>
 * This returns the total number of whole seconds in the duration.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @return the whole seconds part of the length of the duration, positive or negative
 */
public long toSeconds() {
    return seconds;
}

Solution 3 - Java

Because Duration >[...] models a quantity or amount of time in terms of seconds and nanosecond [...]

therefore it offers the two methods

There is no logical "to seconds" since it already is in seconds.

Solution 4 - Java

Quote from http://tutorials.jenkov.com/java-date-time/duration.html:

> You might be asking yourself if there is not a toSeconds() method. > There isn't because that is the same as the seconds part of the > Duration. You can obtain the seconds part of the Duration using the > getSeconds() method as explained earlier.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - JavaSweeperView Answer on Stackoverflow
Solution 2 - JavaJB NizetView Answer on Stackoverflow
Solution 3 - Javaluk2302View Answer on Stackoverflow
Solution 4 - JavaGyrotankView Answer on Stackoverflow