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

只愿长相守 提交于 2020-12-29 08:45:48

问题


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?


回答1:


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.




回答2:


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



回答3:


Because Duration

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

therefore it offers the two methods

  • getSeconds()
  • getNano()

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




回答4:


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.



来源:https://stackoverflow.com/questions/42317152/why-does-the-duration-class-not-have-toseconds-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!