Create Java DateTime Instant from microseconds

    long timeMicros = 1_565_245_051_795_306L;
    Instant i = Instant.EPOCH.plus(timeMicros, ChronoUnit.MICROS);
    System.out.println(i);

Output is:

2019-08-08T06:17:31.795306Z

Edit: Rather than dividing and multiplying to convert microseconds to milliseconds and/or seconds I preferred to use the built-in support for microseconds. Also when explicitly adding them to the epoch feels a little hand-held.

You already know how to convert Instant to LocalDateTime, you’ve shown it in the question, so I am not repeating that.

Edit:

Do you have a solution to get the timeMicros back from the Instant?

There are a couple of options. This way the calculation is not so complicated, so I might do:

    long microsBack = TimeUnit.SECONDS.toMicros(i.getEpochSecond())
            + TimeUnit.NANOSECONDS.toMicros(i.getNano());
    System.out.println(microsBack);

1565245051795306

To be more in style with the first conversion you may prefer the slightly shorter:

    long microsBack = ChronoUnit.MICROS.between(Instant.EPOCH, i);

Edit: Possibly nit-picking, but also to avoid anyone misunderstanding: LocalDateTime has had nanosecond precision always. Only the now method had millisecond precision on Java 8. I read somewhere that from Java 9 the precision varies with the platform, but you are right, microsecond precision seems typical.

Leave a Comment