Java中的 Calendar set() 方法及示例
Calendar 类中的set(int calndr_field , int new_val )方法用于将 calndr_field 值设置为 new_val。此日历的旧字段被新字段替换。
句法:
public void set(int calndr_field, int new_val)
参数:该方法有两个参数:
- calndr_field :这是日历类型,是指要更改的日历字段。
- new_val :这是指要替换的新值。
返回值:该方法不返回任何值。
下面的程序说明了 Calendar 类的 set() 方法的工作原理:
示例 1:
// Java code to illustrate
// set() method
import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
// Creating a calendar
Calendar calndr = Calendar.getInstance();
// Displaying the month
System.out.println("The Current Month is: "
+ calndr.get(
Calendar.MONTH));
// Replacing with a new value
calndr.set(Calendar.MONTH, 11);
// Displaying the modified result
System.out.println("Altered Month is: "
+ calndr.get(
Calendar.MONTH));
}
}
输出:
The Current Month is: 1
Altered Month is: 11
示例 2:
// Java code to illustrate
// set() method
import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
// Creating a calendar
Calendar calndr = Calendar.getInstance();
// Displaying the Year
System.out.println("The Current year is: "
+ calndr.get(
Calendar.YEAR));
// Replacing with a new value
calndr.set(Calendar.YEAR, 1996);
// Displaying the modified result
System.out.println("Altered year is: "
+ calndr.get(
Calendar.YEAR));
}
}
输出:
The Current year is: 2019
Altered year is: 1996
参考: https: Java/util/Calendar.html#set-int-int-