Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 750
Ali Avatar asked Feb 18 '17 15:02

Ali


People also ask

Can Java duration be negative?

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.


2 Answers

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.

like image 173
Sweeper Avatar answered Sep 19 '22 13:09

Sweeper


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; } 
like image 23
JB Nizet Avatar answered Sep 19 '22 13:09

JB Nizet