📜  Java中的即时 toEpochMilli() 方法及示例

📅  最后修改于: 2022-05-13 01:54:23.424000             🧑  作者: Mango

Java中的即时 toEpochMilli() 方法和示例

Instant 类toEpochMilli()方法用于将此瞬间转换为从 1970-01-01T00:00:00Z 的纪元到 long 值的毫秒数。此方法返回该 long 值。
句法:

public long toEpochMilli()

返回:此方法返回自 1970-01-01T00:00:00Z 纪元以来的毫秒数
异常:如果发生数字溢出,此方法将引发ArithmeticException
下面的程序说明了 Instant.toEpochMilli() 方法:
方案一:

Java
// Java program to demonstrate
// Instant.toEpochMilli() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant
            = Instant.parse("2018-12-30T19:34:50.63Z");
 
        // get millisecond value using toEpochMilli()
        long value = instant.toEpochMilli();
 
        // print result
        System.out.println("Millisecond value: "
                           + value);
    }
}


Java
// Java program to demonstrate
// Instant.toEpochMilli() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant = Instant.now();
 
        // current Instant
        System.out.println("Current Instant: "
                           + instant);
 
        // get millisecond value using toEpochMilli()
        long value = instant.toEpochMilli();
 
        // print result
        System.out.println("Millisecond value: "
                           + value);
    }
}



方案二:

Java

// Java program to demonstrate
// Instant.toEpochMilli() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a Instant object
        Instant instant = Instant.now();
 
        // current Instant
        System.out.println("Current Instant: "
                           + instant);
 
        // get millisecond value using toEpochMilli()
        long value = instant.toEpochMilli();
 
        // print result
        System.out.println("Millisecond value: "
                           + value);
    }
}


参考资料:https: Java/time/Instant.html#toEpochMilli()