How to set a specific date in Calendar in Java?
To set a specific date, you can use the set method of the Calendar class. Here is an example code to set a Calendar object to a specified date:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// 创建Calendar对象
Calendar calendar = Calendar.getInstance();
// 设置年份
calendar.set(Calendar.YEAR, 2022);
// 设置月份(注意:月份从0开始,即0表示一月)
calendar.set(Calendar.MONTH, 0);
// 设置日期
calendar.set(Calendar.DAY_OF_MONTH, 1);
// 打印设置后的日期
System.out.println("设置的日期为:" + calendar.getTime());
}
}
In the example code above, a Calendar object is first obtained using the Calendar.getInstance() method. Then, the set method is used to individually set the year, month, and date. Finally, the date that has been set is obtained using the getTime method and printed out.
Note: when setting the month, it is important to remember that the months are numbered starting from 0, where 0 represents January, 1 represents February, and so on.