为什么 Duration class 没有 'toSeconds()' 方法?

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

我正在查看 Java 8 中的 Duration class 并注意到它没有:

long toSeconds();

但它还有所有其他 toXXXXX() 来获取天、小时、分钟、毫秒、纳秒。我确实看到 getSeconds() 方法 returns 此持续时间对象内的秒数。还有一个 get(TemporalUnit unit) 方法来获取持续时间作为请求的时间单位。但是为什么不保持 toSeconds() 方法的一致性呢?

这是一个已知问题,其修复计划于 Java 9:https://bugs.openjdk.java.net/browse/JDK-8142936

在 Java 9、toSeconds 中添加了新方法。参见 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;
}

因为Duration

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

因此它提供了两种方法

没有合乎逻辑的“到秒”,因为它已经秒。

让我们看看docs怎么说:

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

这基本上意味着用于存储表示的时间量的单位是。例如,要存储持续时间 5 分钟和 10 纳秒,则存储 300(秒)和 10(纳秒)。因此,不需要将 转换为 秒。您使用 getSeconds().

得到

明白我的意思了吗?所有其他方法将 转换为 相应的单位:天、分钟、小时...这就是为什么它们以 to 开头,意思是 convertedTo。由于您不需要进行转换以获取以秒为单位的持续时间,因此 returns 以秒为单位的持续时间以 get.

开头的方法

引自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.