Create Java DateTime Instant from microseconds

前端 未结 1 1600
礼貌的吻别
礼貌的吻别 2020-12-19 22:46

There has been changes in Java Date & Time API Since Java 9. LocalDateTime now has microseconds precision.

Java 9 has a fresh implementation of ja

相关标签:
1条回答
  • 2020-12-19 23:45
        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.

    0 讨论(0)
提交回复
热议问题