Fix Java Calendar.add Error
If you find the use of the add method in the Calendar class in Java to be invalid, it may be due to incorrect parameter passing or incorrect order.
The solution is as follows:
- Make sure to pass the correct parameters – the first parameter for the add method should be the field (such as Calendar.YEAR, Calendar.MONTH, etc.), and the second parameter should be the value to add (it can be a negative number to subtract).
- Make sure to properly set the initial values of the Calendar instance before calling the add method, such as setting the values of the year, month, and day fields using the set method.
- Make sure to call the add method before retrieving the value of the corresponding field to ensure the accuracy of the calculation result.
Here is a simple example code:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("当前日期:" + calendar.getTime());
// 增加1年
calendar.add(Calendar.YEAR, 1);
System.out.println("增加1年后的日期:" + calendar.getTime());
// 减少1个月
calendar.add(Calendar.MONTH, -1);
System.out.println("减少1个月后的日期:" + calendar.getTime());
}
}
By following the above method, you can ensure the correct usage of the Calendar class’s add method for manipulating dates.