Date clone() method in Java with Examples

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 does not return any values.

Below programs illustrate the use of clone() Method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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–



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.