Search code examples
javaepochinfluxdb

java epoch time convertor


I have the following date: 2016-08-08T00:45:02.370294075Z

I am trying to convert it to epoch using .getMillis() but it results in loss of precision: 1470617102370. My goal is to convert it to influxdb wire format.

Is there any other way to do that?


Solution

  • tl;dr

    2016-08-08T00:45:02.370294075Z has nanoseconds.

    2016-08-08T00:45:02.370Z has milliseconds.

    Instant

    The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. So up to nine digits in the decimal fraction.

    Instant instant = Instant.parse( "2016-08-08T00:45:02.370294075Z" ) ;
    

    Milliseconds

    Milliseconds is a coarser granularity than nanoseconds, providing up to three digits of decimal fraction. So extracting a count of milliseconds from epoch (1970-01-01T00:00:00Z) will of course mean data loss, the truncation of any decimal digits in positions six through nine.

    long millisecondsSinceEpoch = instant.toEpochMilli() ;  // 2016-08-08T00:45:02.370Z
    

    Nanoseconds

    The influxdb seems to write a timestamp as a number of nanoseconds from epoch of start of 1970 UTC, though the documentation fails to say so explicitly.

    The Instant class does not render a count from epoch in nanoseconds, but you can calculate one. An Instant is made of a number of while seconds since epoch plus a number of nanoseconds in the fraction of second. So multiply the first by a billion and add the second.

    Notice the L appended to the one billion to cast the calculation as a long rather than an int.

    long nanosecondsSinceEpoch = ( instant.getEpochSecond() * 1_000_000_000L ) + instant.getNano() ;