📜  Java中的 Date toInstant() 方法及示例

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

Java中的 Date toInstant() 方法及示例

Java中 Date 类的toInstant()方法用于将 Date 对象转换为 Instant 对象。在转换过程中会创建一个 Instant,用于表示时间线上与此日期相同的点。

句法:

public Instant toInstant()

参数:该方法不带任何参数。

返回值:该方法返回一个Instant ,表示时间线上与此日期相同的点。

下面的程序说明了Java中 toInstant() 方法的使用:
示例 1:

// Java code to demonstrate
// toInstant() method of Date class
  
import java.util.Date;
import java.util.Calendar;
import java.time.Instant;
  
public class GfG {
    public static void main(String args[])
    {
        // Creating a Calendar object
        Calendar c1 = Calendar.getInstance();
  
        // Set Month
        // MONTH starts with 0 i.e. ( 0 - Jan)
        c1.set(Calendar.MONTH, 00);
  
        // Set Date
        c1.set(Calendar.DATE, 30);
  
        // Set Year
        c1.set(Calendar.YEAR, 2019);
  
        // Creating a date object
        // with specified time.
        Date dateOne = c1.getTime();
  
        Instant inst = dateOne.toInstant();
  
        System.out.println(
            "Original Date: "
            + dateOne.toString());
        System.out.println(
            "Instant: " + inst);
    }
}
输出:
Original Date: Wed Jan 30 06:01:46 UTC 2019
Instant: 2019-01-30T06:01:46.730Z

示例 2:

// Java code to demonstrate
// clone() method of Date class
  
import java.util.Date;
import java.util.Calendar;
import java.time.Instant;
  
public class GfG {
    public static void main(String args[])
    {
        // Creating a Calendar object
        Calendar c1 = Calendar.getInstance();
  
        // Set Month
        // MONTH starts with 0 i.e. ( 0 - Jan)
        c1.set(Calendar.MONTH, 06);
  
        // Set Date
        c1.set(Calendar.DATE, 12);
  
        // Set Year
        c1.set(Calendar.YEAR, 1996);
  
        // Creating a date object
        // with specified time.
        Date dateOne = c1.getTime();
  
        Instant inst = dateOne.toInstant();
  
        System.out.println(
            "Original Date: "
            + dateOne.toString());
        System.out.println(
            "Instant: " + inst);
    }
}
输出:
Original Date: Fri Jul 12 06:01:49 UTC 1996
Instant: 1996-07-12T06:01:49.766Z

参考: https: Java/util/Date.html#toInstant–