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


Java Date clone()用法及代碼示例


Java中的Date類的clone()方法返回傳遞的Date對象的重複項。此重複項隻是給定Date對象的淺拷貝。

用法:

public Object clone()

參數:該方法不接受任何參數。


返回值:該方法不返回任何值。

以下示例程序旨在說明clone()方法的使用:

示例1:

// Java code to demonstrate 
// clone() method of Date class 
  
import java.util.Date; 
import java.util.Calendar; 
  
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, 11); 
  
        // Set Date 
        c1.set(Calendar.DATE, 05); 
  
        // Set Year 
        c1.set(Calendar.YEAR, 1996); 
  
        // Creating a date object 
        // with specified time. 
        Date dateOne = c1.getTime(); 
  
        Object dateTwo = dateOne.clone(); 
  
        System.out.println("Original Date: "
                           + dateOne.toString()); 
        System.out.println("Cloned Date: "
                           + dateTwo.toString()); 
    } 
}
輸出:
Original Date: Thu Dec 05 05:39:04 UTC 1996
Cloned Date: Thu Dec 05 05:39:04 UTC 1996

示例2:

// Java code to demonstrate 
// clone() method of Date class 
  
import java.util.Date; 
import java.util.Calendar; 
  
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(); 
  
        Object dateTwo = dateOne.clone(); 
  
        System.out.println("Original Date: "
                           + dateOne.toString()); 
        System.out.println("Cloned Date: "
                           + dateTwo.toString()); 
    } 
}
輸出:
Original Date: Wed Jan 30 05:39:10 UTC 2019
Cloned Date: Wed Jan 30 05:39:10 UTC 2019

參考: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#clone–



相關用法


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