我正在尝试将Calendar对象的月份设置为其他月份。但是当我使用两种不同的方法时,我得到的输出不同。当月是六月,即Calendar.MONTH = 5
Calendar previousCal = Calendar.getInstance();
previousCal.set(Calendar.MONTH,Calendar.MONTH-1);
int calMonth = previousCal.get(Calendar.MONTH);
System.out.println("CAL month=:"+calMonth);
**Output Value printed = 1**
Calendar newpreviousCal = Calendar.getInstance();
int newPrevMonth = newpreviousCal.get(Calendar.MONTH);
newPrevMonth = newPrevMonth -1;
previousCal.set(Calendar.MONTH,newPrevMonth);
int newcalMonth = previousCal.get(Calendar.MONTH);
System.out.println("CAL month Nw=:"+newcalMonth);
**Output Value printed = 4**
答案 0 :(得分:1)
这一行
previousCal.set(Calendar.MONTH,Calendar.MONTH-1);
将给定日历的月份设置为1
,因为Calendar.MONTH
是一个常量(2
),并且您从中减去1
。
如果您的目标是从日历的月份字段中减去一个,则需要get
和set
:
previousCal.set(Calendar.MONTH, previousCal.get(Calendar.MONTH) - 1);
......当然,请使用add
:
previousCal.add(Calendar.MONTH, -1);