Skip to content
Related Articles

Related Articles

Date clone() method in Java with Examples
  • Last Updated : 01 Nov, 2020

The clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object.
Syntax: 
 

public Object clone()

Parameters: The method does not accept any parameters.
Return Value: The method returns a clone of the object.
Below programs illustrate the use of clone() Method:
Example 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());
    }
}


Output: 

Original Date: Thu Dec 05 05:39:04 UTC 1996
Cloned Date: Thu Dec 05 05:39:04 UTC 1996


 

Example 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());
    }
}


Output: 

Original Date: Wed Jan 30 05:39:10 UTC 2019
Cloned Date: Wed Jan 30 05:39:10 UTC 2019


 

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :