为什么持续时间类没有“toSeconds()”方法?
2022-08-31 15:51:57
我正在查看Java 8中的持续时间类,并注意到它没有:
long toSeconds();
但它有所有其他的天,小时,分钟,毫,纳米。我确实看到一个返回此持续时间对象中的秒数的方法。还有一种方法可以将持续时间作为请求的时间单位。但是,为什么不保持方法的一致性呢?toXXXXX()getSeconds()get(TemporalUnit unit)toSeconds()
我正在查看Java 8中的持续时间类,并注意到它没有:
long toSeconds();
但它有所有其他的天,小时,分钟,毫,纳米。我确实看到一个返回此持续时间对象中的秒数的方法。还有一种方法可以将持续时间作为请求的时间单位。但是,为什么不保持方法的一致性呢?toXXXXX()getSeconds()get(TemporalUnit unit)toSeconds()
让我们看看文档是怎么说的:
此类以秒和纳秒为单位对时间量或量进行建模。
这基本上意味着用于存储所表示的时间量的单位是秒。例如,若要将持续时间存储 5 分钟和 10 纳秒,则存储 300(秒)和 10(纳秒)。因此,无需转换为秒。您可以使用 获得秒数。getSeconds()
明白我在这里的意思吗?所有其他方法转换为相应的单位:天,分钟,小时...这就是为什么它们以 开头,意思是。由于您无需执行转换即可获取以秒为单位的持续时间,因此返回持续时间(以秒为单位)的方法以 开头。toconvertedToget
这是一个已知问题,已安排在 Java 9 中修复:https://bugs.openjdk.java.net/browse/JDK-8142936
Java 9 中新增了新方法。请参阅源代码。toSeconds
/**
* 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;
}