Convert Instant to microseconds from Epoch time

Michal Kordas :

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?

pdxleif :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=435648&siteId=1