I'm trying to standardize time stamp format for my project, where the source reports in microsecond precision. I'm trying to find out whether there is a clean or minimal approach that does not require using handwritten constants.
Best Answer
Thanks for the suggestions. This is the cleanest I could come up with:
static Instant getInstantFromMicros(long microsSinceEpoch) {return Instant.ofEpochSecond(TimeUnit.MICROSECONDS.toSeconds(microsSinceEpoch), TimeUnit.MICROSECONDS.toNanos(Math.floorMod(microsSinceEpoch, TimeUnit.SECONDS.toMicros(1))));}static Instant getInstantFromNanos(long nanosSinceEpoch) {return Instant.ofEpochSecond(0L, nanosSinceEpoch);}
Test Cases:
System.out.println(getInstantFromMicros(1_500_000_000_123_456L));// 2017-07-14T02:40:00.123456ZSystem.out.println(getInstantFromNanos(1_500_000_000_123_456_789L));// 2017-07-14T02:40:00.123456789Z
This is simplified methods of the accepted answer.
static final long NANOS_PER_SECOND = TimeUnit.SECONDS.toNanos(1L);static final long NANOS_PER_MICROSECOND = TimeUnit.MICROSECONDS.toNanos(1L);/*** Obtains an instance of Instant using nanoseconds from the epoch of 1970-01-01T00:00:00Z.** @param epochNano the number of nanoseconds from 1970-01-01T00:00:00Z.* @return an instant; not {@code null}.*/public static Instant instantOfEpochNano(final long epochNano) {return Instant.ofEpochSecond(0L, epochNano);}/*** Obtains an instance of Instant using microseconds from the epoch of 1970-01-01T00:00:00Z.** @param epochMicro the number of microseconds from 1970-01-01T00:00:00Z.* @return an instant; not {@code null}.* @see #instantOfEpochNano(long)*/public static Instant instantOfEpochMicro(final long epochMicro) {return instantOfEpochNano(Math.multiplyExact(epochMicro, NANOS_PER_MICROSECOND));}