📜  Java中的 GregorianCalendar clone() 方法

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

Java中的 GregorianCalendar clone() 方法

GregorianCalendar 类的Java.util.GregorianCalendar.clone()方法用于创建一个新对象并将GregorianCalendar 实例的所有内容复制到新对象中。

句法:

public Object clone()

参数:此函数不接受任何参数。

返回值:此函数返回对象的副本。

例子:

Input: Mon Jul 23 14:35:27 UTC 2018
Output: Mon Jul 23 14:35:27 UTC 2018

Input: Current Date and Time is Mon Jul 23 14:35:27 UTC 2018
       cal1.add((GregorianCalendar.MONTH), -7);
       cal1.clone();
Output: Sat Dec 23 14:36:42 UTC 2017

下面的程序说明了Java.util.GregorianCalendar.clone() 方法:
方案一:

// Java Program to illustrate GregorianCalendar.clone()
// function 
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a new calendar
        GregorianCalendar cal = (GregorianCalendar)
                   GregorianCalendar.getInstance();
  
        // Display the date and time
        System.out.println("Date and Time in"
                +" cal object : "+ cal.getTime());
  
        GregorianCalendar newcalender = 
                          new GregorianCalendar();
  
        // Cloning the object
        newcalender = (GregorianCalendar)cal.clone();
  
        // Display date and time
        System.out.println("Date and Time in"+
        " newcalender object : "+ newcalender.getTime());
    }
}
输出:
Date and Time in cal object : Fri Aug 03 11:01:24 UTC 2018
Date and Time in newcalender object : Fri Aug 03 11:01:24 UTC 2018

方案二:

// Java Program to illustrate 
// GregorianCalendar.clone()
// function 
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a new calendar
        GregorianCalendar cal1, cal2;
  
        cal1 = (GregorianCalendar)GregorianCalendar.
                                     getInstance();
  
        // Display the current date and time
        System.out.println("Current Date and Time : "
                                   + cal1.getTime());
        // Modifying the current date and time
        cal1.add((GregorianCalendar.MONTH), 2);
  
        // Cloning the object
        cal2 = (GregorianCalendar)cal1.clone();
  
        // Display date and time
        System.out.println("New Date and Time : "
                           + cal2.getTime());
    }
}
输出:
Current Date and Time : Fri Aug 03 11:01:27 UTC 2018
New Date and Time : Wed Oct 03 11:01:27 UTC 2018

参考: https: Java/util/GregorianCalendar.html#clone()