我是靠谱客的博主 犹豫冰棍,这篇文章主要介绍Calendar set时间时,天数加1,月份的改变,现在分享给大家,希望可以做个参考。

Calendar   set方法:

先看源码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/** * 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方法:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
复制代码
复制代码
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()));
测试结果如下:


最后

以上就是犹豫冰棍最近收集整理的关于Calendar set时间时,天数加1,月份的改变的全部内容,更多相关Calendar内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(88)

评论列表共有 0 条评论

立即
投稿
返回
顶部