Calendar Field Manipulation

Environment

JDK 1.6.0_45

Situation

// Method-A
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.MAY, 31);
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, Calendar.JUNE);
System.out.println(cal.getTime());
cal.set(Calendar.DAY_OF_MONTH, 30);
System.out.println(cal.getTime());

System.out.println("======");

// Method-B
cal.set(2015, Calendar.MAY, 31);
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_MONTH, 30);
System.out.println(cal.getTime());

Result (Different results)

Sun May 31 02:47:52 CST 2015
Wed Jul 01 02:47:52 CST 2015
Thu Jul 30 02:47:52 CST 2015
======
Tue Jun 30 02:47:52 CST 2015

Reason

According to the JDK document, under the Field Manipulation section:

“set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar’s time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations…”

The process of Method-A would be:

2015/5/31→2015/6/31 auto convert to 2015/7/1→2015/7/30

The process of Method-B would be (Not trigger recomputing until calling getTime):

2015/5/31→2015/6/31→2015/6/30

Reference

http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s