Calendar類中的roll(int calndr_field,int amt)方法用於對傳遞的日曆字段進行操作,方法是將傳遞的數量添加到特定的日曆字段,而無需更改大的字段值。注意:必須添加正數,而必須減去負數。
用法:
public void roll(int calndr_field, int amt)
參數:該方法有兩個參數:
- calndr_field:這是“日曆”類型,是指要操作的日曆字段。
- 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)
相關用法
- Java Calendar set()用法及代碼示例
- Java Calendar add()用法及代碼示例
- Java Calendar get()用法及代碼示例
- Java Calendar getFirstDayOfWeek()用法及代碼示例
- Java Calendar setTimeInMillis()用法及代碼示例
- Java Calendar getActualMaximum()用法及代碼示例
- Java Calendar getDisplayName()用法及代碼示例
- Java Calendar getInstance()用法及代碼示例
- Java Calendar getTimeZone()用法及代碼示例
- Java Calendar setTimeZone()用法及代碼示例
- Java Calendar getGreatestMinimum()用法及代碼示例
- Java Calendar getDisplayNames()用法及代碼示例
- Java Calendar internalGet()用法及代碼示例
- Java Calendar setLenient()用法及代碼示例
- Java Calendar isLenient()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Calendar roll(int calndr_field, int amt) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。