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.
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.123456Z
System.out.println(getInstantFromNanos(1_500_000_000_123_456_789L));
// 2017-07-14T02:40:00.123456789Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With