当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。