如何从微秒或纳秒创建Java Instant?

tv6aics1  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(136)

我正试图为我的项目标准化时间戳格式,其中源代码以微秒精度报告。我正试图找出是否有一种干净或最小的方法,不需要使用手写常量。

hts6caw3

hts6caw31#

谢谢你的建议。这是我能想到的最干净的:

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);
}

测试用例:

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
yftpprvb

yftpprvb2#

这是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));

    }

相关问题