14

有人可以解释Instant.getEpochSecondInstant.toEpochMilli命名背后的理由吗?我能想到的唯一原因是将瞬间的内部表示为相对于纪元的秒和相对于该秒的纳秒,而毫秒是根据这两个值计算的。

但是你为什么要让这样的实现细节泄漏到新的 API 中呢?

4

3 回答 3

12

I'd have to guess but I'd agree with you:

  • getEpochSecond() indicates a mere getter, i.e. it just returns the value which is stored in that instance
  • toEpochMilli() on the other hand would calculate its return value, much like toString() would not return a stored string but build in on-the-fly every time the method is called

That convention actually is documented here: http://docs.oracle.com/javase/tutorial/datetime/overview/naming.html

The reason for this convention probably is related to the JavaBeans specification, i.e. epochSecond would be a (readonly) property of Instant whereas epochMilli is a different representation but not a property.

于 2014-08-21T13:20:42.637 回答
4

getter 返回Temporal对象的一部分(如Instant),而to*方法返回它的转换版本:

  • getEpochSecond()返回从 1970-01-01T00:00:00Z 的 Java 纪元开始的秒数。
  • getNanos()返回纳秒的秒部分Instant
  • toEpochMilli()返回Instant转换为毫秒(即seconds * 1000 + nanoseconds / 1,000,000
于 2014-08-21T13:25:35.100 回答
0

方便?用于 UNIX 时间兼容性的 EpochSeconds,用于 Java 日期兼容性的 EpochMilli,从我的脑海中浮现。

编辑:哦,我什至不明白这个问题,这就是为什么一个是“get”而另一个是“to”:也许是为了提醒你第二个进行转换并且可能会失败。

于 2014-08-21T13:22:47.427 回答