java.util.Calendar clear(int field)

Description :

This java tutorial shows how to use the clear(int field) method of Calendar class of java.util package. This method sets the given calendar field value and the time value (millisecond offset from the Epoch) of this Calendar undefined. This means that isSet(field) will return false, and the date and time calculations will treat the field as if it had never been set. A Calendar implementation class may use the field’s specific default value for date and time calculations.

Method Syntax :

public final void clear(int field)

Parameter Input :

 

DataType Parameter Description
int field The calendar field this method will clear

 

Method Returns :

This method returns void.

Compatibility Version :

Requires Java 1.1 and up

Exception :

N/A

Discussion :

The Calender clear(int field) method is used as the name suggest to clear a specific field of the Calendar object. This is helpful in working with set() method of Calendar class. For example, if we want to set the year field of this Calendar object, we would be calling set(Calendar.YEAR,desired_value) and the rest of the Calendar field would be the same. So if the month field that the Calendar object currently holds is undesired, we can call set(Calendar.MONTH).

Java Code Example :

This java example source code demonstrates the use of clear(int field)  method of Calendar class.

package com.javatutorialhq.java.examples;

import java.util.Calendar; import java.util.Date;

/* * This example source code demonstrates the use of * clear(int field) method of Calendar class */

public class CalendarClearFieldExample {

public static void main(String

[] args) throws InterruptedException {

Calendar cal = Calendar.getInstance(); // Printing the current time System.out.println("Current time:" + cal.getTime());

// set the time using the 1st overloaded method cal.set(Calendar.YEAR, 2032); // set the year cal.set(Calendar.MONTH, 11); // set the month System.out.println("Time After set:"+cal.getTime());

// clear the calendar object Month field cal.clear(Calendar.MONTH); System.out.println(cal.getTime());

// set the month cal.set(Calendar.MONTH, 7); // set the year System.out.println("Time after clear and set:"+cal.getTime());

}

}

Sample Output :

Running the clear(int field) method example source code of Calendar class will give you the following output:

Calendar clear(int field) method example

Calendar clear(int field) method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :