要从纪元微秒或纳秒创建Java Instant,可以使用Instant类的静态方法ofEpochMilli()和ofEpochNano()。这两个方法分别接受一个表示从纪元开始的毫秒数或纳秒数作为参数,并返回一个对应的Instant对象。
示例代码如下:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
long epochMillis = 1634567890123L;
long epochNanos = 1634567890123456789L;
Instant instantFromMillis = Instant.ofEpochMilli(epochMillis);
Instant instantFromNanos = Instant.ofEpochNano(epochNanos);
System.out.println("Instant from milliseconds: " + instantFromMillis);
System.out.println("Instant from nanoseconds: " + instantFromNanos);
}
}
输出结果:
Instant from milliseconds: 2021-10-18T10:11:30.123Z
Instant from nanoseconds: 2021-10-18T10:11:30.123456789Z
在这个例子中,我们使用了一个表示从纪元开始的毫秒数和纳秒数来创建Instant对象。通过调用Instant类的ofEpochMilli()方法和ofEpochNano()方法,我们可以将这些数值转换为对应的Instant对象。最后,我们打印了这两个Instant对象的值。
需要注意的是,Instant类是不可变的,表示时间线上的一个特定点。它以ISO-8601的格式表示,并且使用UTC时区。
没有搜到相关的文章