Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale behind Instant.getEpochSecond vs Instant.toEpochMilli [closed]

Tags:

java

java-time

Can somebody explain the rationale behind the naming of Instant.getEpochSecond vs. Instant.toEpochMilli? The only reason I can think of is the internal representation of an instant as seconds relative to epoch and nano seconds relative to that second whereas the milli seconds are calculated from those two values.

But why would you let such an implementation detail leak into a new API?

like image 878
ooxi Avatar asked Aug 21 '14 13:08

ooxi


People also ask

What is getEpochSecond?

getEpochSecond. public long getEpochSecond() Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. The epoch second count is a simple incrementing count of seconds where second 0 is 1970-01-01T00:00:00Z.

What is Instant Java?

Java Instant class is used to represent a specific moment on the time line. This might be used to record event time-stamps in the application. This class is immutable and thread-safe. Unlike the old java.util.Date which has milliseconds precision, an Instant has nanoseconds precision.


2 Answers

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.

like image 179
Thomas Avatar answered Sep 18 '22 11:09

Thomas


The getters return parts of an Temporal object (like Instant), while the to* methods return a converted version of it:

  • getEpochSecond() returns the gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
  • getNanos() returns the nanoseconds-of-second-part of the Instant
  • toEpochMilli() returns the Instant converted into milliseconds (i.e. seconds * 1000 + nanoseconds / 1,000,000)
like image 23
isnot2bad Avatar answered Sep 18 '22 11:09

isnot2bad