Calendar set时间时,天数加1,月份的改变

Calendar   set方法:

先看源码:

/**
 * Sets the values for the calendar fields YEAR,
 * MONTH, and DAY_OF_MONTH.
 * Previous values of other calendar fields are retained.  If this is not desired,
 * call {@link #clear()} first.
 *
 * @param year the value used to set the YEAR calendar field.
 * @param month the value used to set the MONTH calendar field.
 * Month value is 0-based. e.g., 0 for January.
 * @param date the value used to set the DAY_OF_MONTH calendar field.
 * @see #set(int,int)
 * @see #set(int,int,int,int,int)
 * @see #set(int,int,int,int,int,int)
 */
public final void set(int year, int month, int date)
{
    set(YEAR, year);
    set(MONTH, month);
    set(DATE, date);
}

问题来了,当调用set时(例如2016-08-31),date加1,month会不会改变。

先测试一下and方法:

Calendar cal = Calendar.getInstance();
//设置时间2016-08-31
cal.set(2016,Calendar.AUGUST,31);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

System.out.println(sdf.format(cal.getTime()));
//add 天数加1
cal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println(sdf.format(cal.getTime()));
//set 设置天数
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(sdf.format(cal.getTime()));
输出结果如下:


再测试一下date+1:

Calendar cal = Calendar.getInstance();
//设置时间2016-08-31
cal.set(2016,Calendar.AUGUST,31);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

System.out.println(sdf.format(cal.getTime()));

Calendar cal2 = Calendar.getInstance();

cal2.set(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH)+1);
System.out.println(sdf.format(cal2.getTime()));

cal2.set(2016,Calendar.AUGUST,360);
System.out.println(sdf.format(cal2.getTime()));
测试结果如下:


你可能感兴趣的:(Java,Calendar,Java)