Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create Java Instant from epoch microseconds or nanoseconds?

Tags:

java

timestamp

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.

like image 346
ayush3504 Avatar asked Jan 24 '26 23:01

ayush3504


1 Answers

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
like image 76
ayush3504 Avatar answered Jan 27 '26 14:01

ayush3504



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!