當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Calendar roll()用法及代碼示例


Calendar類中的roll(int calndr_field,boolean up_down)方法用於通過上下移動傳遞的字段單個時間單位來對傳遞的日曆字段進行操作。這涉及在不更改較大字段的情況下對時間字段進行加法或減法。

用法:

public abstract void roll(int calndr_field, boolean up_down)

參數:該方法有兩個參數:


  • calndr_field:這是日曆類型,是指要對其進行操作的日曆字段。
  • up_down:這是布爾類型,用於指示是向上或向下移動calndr_field還是增大或減小。 true表示添加時間單位,false表示減去時間單位。

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

以下示例程序旨在說明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 
        // false indicates subtraction 
        calndr.roll(Calendar.YEAR, false); 
  
        // Displaying the result after operation 
        System.out.println("The New Year is: "
                           + calndr.get( 
                                 Calendar.YEAR)); 
  
        // Incrementing the year 
        // true indicates addition 
        calndr.roll(Calendar.YEAR, true); 
  
        // 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: 2018
The new year is: 2019

示例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 
        // true indicates addition 
        calndr.roll(Calendar.MONTH, true); 
  
        // Displaying the result after operation 
        System.out.println("The New Month is: "
                           + calndr.get( 
                                 Calendar.MONTH)); 
  
        // Decrementing the month 
        // false indicates subtraction 
        calndr.roll(Calendar.MONTH, false); 
  
        // Displaying the result after operation 
        System.out.println("The new month is: "
                           + calndr.get( 
                                 Calendar.MONTH)); 
    } 
}
輸出:
The Current Month is: 1
The New Month is: 2
The new month is: 1

參考: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#roll-int-boolean-



相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Calendar roll() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。