Calendar clear(int cal_field) Method in Java with Examples

The clear(int cal_field) method in Calendar class is used to set a given calendar field value and the time value of this Calendar undefined.
Note: Implementation of calendar class may use default field values for date and time calculations.

Syntax:

public final void clear(int cal_field)

Parameters: The method takes one parameter cal_field of Integer type and refers to the field value that is to be made undefined.



Return Value: The method does not return any value.

Below programs illustrate the working of clear() Method of Calendar class:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to illustrate clear() Method
  
import java.util.Calendar;
  
public class CalendarClassDemo {
    public static void main(String args[])
    {
        // Creating a calendar object
        Calendar calndr = Calendar.getInstance();
  
        // Displaying the Current Date
        System.out.println("Current Date&Time: "
                           + calndr.getTime());
  
        // Clear method for undefining the month
        // of the calendar
        calndr.clear(Calendar.MONTH);
  
        // Displaying the final result
        System.out.println("After clear method: "
                           + calndr.getTime());
    }
}

chevron_right


Output:

Current Date&Time: Wed Mar 27 09:03:26 UTC 2019
After clear method: Sun Jan 27 09:03:26 UTC 2019

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to illustrate clear() Method
  
import java.util.Calendar;
  
public class CalendarClassDemo {
    public static void main(String args[])
    {
        // Creating a calendar object
        Calendar calndr = Calendar.getInstance();
  
        // Displaying the Current Date
        System.out.println("Current Date&Time: "
                           + calndr.getTime());
  
        // Clear method for undefining the year
        // of the calendar
        calndr.clear(Calendar.YEAR);
  
        // Displaying the final result
        System.out.println("After clear method: "
                           + calndr.getTime());
    }
}

chevron_right


Output:

Current Date&Time: Wed Mar 27 09:03:32 UTC 2019
After clear method: Fri Mar 27 09:03:32 UTC 1970

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#clear(int)



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.