当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-



相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Calendar set() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。