Java Instant ofEpochSecond()方法及示例
在Instant类中,有两种类型的ofEpochSecond()方法,取决于传递给它的参数。
ofEpochSecond(long epochSecond)
ofEpochSecond() 方法是 Instant 类的方法,用来返回一个Instant的实例,该方法的参数是从1970-01-01T00:00:00Z的纪元开始计算的秒数,纳秒域被设置为零。
语法
public static Instant ofEpochSecond(long epochSecond)
参数: 该方法只接受一个参数 epochSecond ,即从1970-01-01T00:00:00Z开始的秒数。
返回值: 该方法使用作为参数传递的秒数返回 瞬间 。
异常: 如果瞬时超过最大或最小瞬时,该方法会抛出以下异常 DateTimeException 。
以下程序说明了ofEpochSecond()方法:
程序1 :
// Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value long epochSecond = 1200000l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond); // print results System.out.println("Instant: " + result); }}
输出:
Instant: 1970-01-14T21:20:00Z
ofEpochSecond(long epochSecond, long nanoAdjustment)
ofEpochSecond() 方法是 Instant 类的一个方法,用于返回Instant的一个实例,该方法的参数为从1970-01-01T00:00:00Z开始计算的秒,纳秒也作为参数被传递,这将改变秒和纳秒的值,以确保存储的纳秒在0到999, 999, 999范围内。
语法
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)
参数: 该方法接受两个参数 epochSecond 和 nanoAdjustment ,前者是1970-01-01T00:00:00Z的秒数,后者是对秒数的纳秒调整,可正可负。
返回值: 该方法使用作为参数传递的秒数返回 即时值 。
异常: 该方法会抛出以下异常。
DateTimeException – 如果瞬间超过了最大或最小的瞬间。ArithmeticException – 如果发生数字溢出。以下程序说明了ofEpochSecond()方法:
程序1 :
// Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value and nanoadjustment value long epochSecond = 1200000000l; long nanoadjustment = 999999l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond, nanoadjustment); // print results System.out.println("Instant: " + result); }}输出:
Instant: 2008-01-10T21:20:00.000999999Z
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long, long)
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long)
