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


Java Calendar roll(int calndr_field, int amt)用法及代码示例


Calendar类中的roll(int calndr_field,int amt)方法用于对传递的日历字段进行操作,方法是将传递的数量添加到特定的日历字段,而无需更改大的字段值。注意:必须添加正数,而必须减去负数。

用法:

public void roll(int calndr_field, int amt)



参数:该方法有两个参数:

  1. calndr_field:这是“日历”类型,是指要操作的日历字段。
  2. amt:这是整数类型,将根据值的符号相加或相减。

返回值:该方法不返回任何值。

以下示例程序旨在说明Calendar类的roll()方法的用法:
范例1:

// Java code to illustrate 
// isSet() 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)); 
  
        // Decrementing the year 
        // by 5 
        calndr.roll(Calendar.YEAR, -5); 
  
        // Displaying the result after the operation 
        System.out.println("The New Year is:"
                           + calndr.get( 
                                 Calendar.YEAR)); 
  
        // Incrementing the year 
        // by 2 
        calndr.roll(Calendar.YEAR, 2); 
  
        // Displaying the result after operation 
        System.out.println("The new year is:"
                           + calndr.get( 
                                 Calendar.YEAR)); 
    } 
}
输出:
The Current Year is:2019
The New Year is:2014
The new year is:2016

范例2:

// Java code to illustrate 
// isSet() 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)); 
  
        // Incrementing the month 
        // by 3 
        calndr.roll(Calendar.MONTH, 3); 
  
        // Displaying the result after operation 
        System.out.println("The New Month is:"
                           + calndr.get( 
                                 Calendar.MONTH)); 
  
        // Decrementing the month 
        // by 1 
        calndr.roll(Calendar.MONTH, -1); 
  
        // Displaying the result after operation 
        System.out.println("The new month is:"
                           + calndr.get( 
                                 Calendar.MONTH)); 
    } 
}
输出:
The Current Month is:2
The New Month is:5
The new month is:4

参考: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#roll(int, %20int)



相关用法


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