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

Calendar   set方法:

先看源码:

/**
 * Sets the values for the calendar fields <code>YEAR</code>,
 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
 * 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 <code>YEAR</code> calendar field.
 * @param month the value used to set the <code>MONTH</code> calendar field.
 * Month value is 0-based. e.g., 0 for January.
 * @param date the value used to set the <code>DAY_OF_MONTH</code> 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()));
测试结果如下:


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值