A personal memo when you want to clear the time part of the date and time data acquired by Calendar.
calenderObj.clear(Calendar.HOUR_OF_DAY);
calenderObj.clear(Calendar.HOUR);
calenderObj.clear(Calendar.MINUTE);
calenderObj.clear(Calendar.SECOND);
calenderObj.clear(Calendar.MILLISECOND);
Write a program and check it.
import java.util.Calendar;
public class CalendarClear {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
sysout(calendar);
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
sysout(calendar);
calendar.clear(Calendar.HOUR_OF_DAY);
sysout(calendar);
}
private static final void sysout(Calendar calc) {
System.out.println("/--------------------");
System.out.println("YEAR:" + calc.get(Calendar.YEAR));
System.out.println("MONTH:" + calc.get(Calendar.MONTH));
System.out.println("DATE:" + calc.get(Calendar.DATE));
System.out.println("HOUR_OF_DAY:" + calc.get(Calendar.HOUR_OF_DAY));
System.out.println("HOUR:" + calc.get(Calendar.HOUR));
System.out.println("MINUTE:" + calc.get(Calendar.MINUTE));
System.out.println("SECOND:" + calc.get(Calendar.SECOND));
System.out.println("MILLISECOND:" + calc.get(Calendar.MILLISECOND));
}
}
The result is this.
/--------------------
YEAR:2017
MONTH:4
DATE:22
HOUR_OF_DAY:17
HOUR:5
MINUTE:25
SECOND:35
MILLISECOND:527
/--------------------
YEAR:2017
MONTH:4
DATE:22
HOUR_OF_DAY:17
HOUR:5
MINUTE:0
SECOND:0
MILLISECOND:0
/--------------------
YEAR:2017
MONTH:4
DATE:22
HOUR_OF_DAY:17
HOUR:5
MINUTE:0
SECOND:0
MILLISECOND:0
The values of HOUR_OF_DAY and HOUR are not cleared. This is the correct description.
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
sysout(calendar);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
//To clear the time part, you have to put it in set.
calendar.set(Calendar.HOUR_OF_DAY, 0);
sysout(calendar);
calendar.clear();
sysout(calendar);
}
It is clearly stated in JavaDoc. Calendar (Java Platform SE 7 )
The HOUR_OF_DAY, HOUR, and AM_PM fields are treated separately and the time resolution rule applies. Clearing any of the> fields does not reset the "hours" in this Calendar. Use set (Calendar.HOUR_OF_DAY, 0) to reset the "hour" value.
Processing result.
/--------------------
YEAR:2017
MONTH:4
DATE:22
HOUR_OF_DAY:17
HOUR:5
MINUTE:27
SECOND:12
MILLISECOND:718
/--------------------
YEAR:2017
MONTH:4
DATE:22
HOUR_OF_DAY:0
HOUR:0
MINUTE:0
SECOND:0
MILLISECOND:0
bonus
calendar.clear();
When you do
/--------------------
YEAR:1970
MONTH:0
DATE:1
HOUR_OF_DAY:0
HOUR:0
MINUTE:0
SECOND:0
MILLISECOND:0
All items are cleared.
Calendar (Java Platform SE 7 )
Set all calendar field and time values (offsets in milliseconds from the epoch) for this calendar to undefined.
Recommended Posts