Java中的日期 clone() 方法及示例
Java中 Date 类的 clone() 方法返回传递的 Date 对象的副本。此副本只是给定 Date 对象的浅表副本。
句法:
public Object clone()
参数:该方法不接受任何参数。
返回值:该方法返回对象的克隆。
下面的程序说明了使用 clone() 方法:
示例 1:
Java
// 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());
}
}
Java
// 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: Thu Dec 05 05:39:04 UTC 1996
Cloned Date: Thu Dec 05 05:39:04 UTC 1996
示例 2:
Java
// 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: Java/util/Date.html#clone–