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?
Checks if this duration is zero length. A Duration represents a directed distance between two points on the time-line and can therefore be positive, zero or negative. This method checks whether the length is zero.
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
.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With