1

I am working on a project which requires timestamps for running threads. In Erlang, when we do now() we get something like

{1529,709564,578215} which represent {megaseconds, seconds, microseconds}

since epoch. So, for two processes spawned at the same time, I can get same microseconds value. Is there a way to replicate this function in Java?

I know about Date.getTime() which gives us the milliseconds since epoch time, but it does not serve the purpose since I cannot get a unique microsecond value from it after dividing by order of magnitude.

Any alternative?

smaug
  • 846
  • 10
  • 26

1 Answers1

2
        System.out.println(Instant.now());

Output just now was:

2018-06-23T05:16:45.768006Z

On the Java 10 on my Mac it gave microsecond precision. Since Java 9 it will on many operating systems, maybe not all. Instant.now() returns an Instant. An Instant is implemented as seconds and nanoseconds since the epoch, and you can get out those individually if you want.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Thanks, it helps. But I am unsure whether Instant.now() outputs in microsecond precision (which Erlang now() does). I was referring to https://stackoverflow.com/a/20689231/4244347 answer while making the above claim. Any explanation/correction is welcome. – smaug Jun 27 '18 at 23:18
  • Java relies on the OS and the hardware for the precision. So does Erlang necessarily. So I would expect it to be the same. I obviously have not tested on all OSs and hardware configurations. – Ole V.V. Jun 28 '18 at 04:30