Search code examples
javadatetimejava-8epochjava-time

Convert Instant to microseconds from Epoch time


In Instant there are methods:

  • toEpochMilli which converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z
  • getEpochSecond which gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

Both of these methods lose precision, e.g. in toEpochMilli JavaDoc I see:

If this instant has greater than millisecond precision, then the conversion drop any excess precision information as though the amount in nanoseconds was subject to integer division by one million.

I don't see corresponding methods to obtain more precise timestamp. How can I get number of micros or nanos from epoch in Java 8?


Solution

  • As part of java.time, there are units under java.time.temporal.ChronoUnit that are useful for getting the difference between two points in time as a number in nearly any unit you please. e.g.

    import java.time.Instant;
    import java.time.temporal.ChronoUnit;
    
    ChronoUnit.MICROS.between(Instant.EPOCH, Instant.now())
    

    gives the microseconds since epoch for that Instant as a long.