當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant–



相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Date toInstant() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。