Calendar.clear()

Date

Calendar.clear(field) Reset the value of field to undefined.

field : Required Calendar field, Year, month , date, hour , minute , second , millseconds.


The method isSet() returns true or false based on the value set for the field or not.

Examples with output
Let us create one calendar object and we will reset the fields by using clear().
package my_proj;
 
import java.util.Calendar;
 
public class my_first {
public static void main(String[] args) {

Calendar my_cal = Calendar.getInstance();// created calendar 

System.out.println(my_cal.clear(Calendar.YEAR));// true
my_cal.clear(Calendar.YEAR); // Clear or reset the year part 
System.out.println(my_cal.clear(Calendar.YEAR));// false
System.out.println(my_cal.clear(Calendar.MONTH));// true 

}
}
Here we have first checked for YEAR by using isSet() and the value we got is true. Then we reset the YEAR value by using clear() and then isSet() reutned false. However clear() has not removed the other field values so we got true when we checked for the field MONTH in last line.

By resetting or clearing HOUR field we are not resetting HOUR_OF_DAY. Check this code with output.
package my_proj;
 
import java.util.Calendar;
 
public class my_first {
public static void main(String[] args) {

Calendar my_cal = Calendar.getInstance();// created calendar 

System.out.println(my_cal.isSet(Calendar.YEAR));// true
my_cal.clear(Calendar.HOUR);
System.out.println(my_cal.isSet(Calendar.HOUR));// false
System.out.println(my_cal.isSet(Calendar.HOUR_OF_DAY));// true 
System.out.println(my_cal.get(Calendar.HOUR_OF_DAY)); // 14

}
}

Resetting all the fields

We can reset all field values to undefined ( or to its specific default field values ) by using clear()
package my_proj;
 
import java.util.Calendar;
 
public class my_first {
public static void main(String[] args) {

Calendar my_cal = Calendar.getInstance();// created calendar 

System.out.println(my_cal.getTime());//
my_cal.clear();
System.out.println(my_cal.getTime());
}
}
Output
Tue Mar 03 16:32:35 IST 2020
Thu Jan 01 00:00:00 IST 1970
set() Date & time tutorials



plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer