Calendar類的add(int字段,int amt)方法用於根據日曆的規則從給定的日曆字段(int字段)中添加或減去特定時間(int amt)。
用法:
public abstract void add(int field, int amt)
參數:該方法有兩個參數:
- field:這是整數類型,是指要在其上執行操作的日曆字段。
- amt:這是整數類型,是指需要減去的時間。
返回值:該方法不返回任何值。
以下示例程序旨在說明Calendar類的add()方法的用法:
示例1:
// Java Code to illustrate add() Method
import java.util.Calendar;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr
= Calendar.getInstance();
// Displaying the Current Date
System.out.println("Current Date: "
+ calndr.getTime());
// Adding 50 days to the
// Current Calendar
calndr.add(Calendar.DATE, 50);
System.out.println("After 50 days: "
+ calndr.getTime());
// Subtracting 6 months from
// the Current calendar
calndr.add(Calendar.MONTH, -6);
System.out.println("6 months ago it was: "
+ calndr.getTime());
// Subtracting 2 year from
// the Current calendar
calndr.add(Calendar.YEAR, -2);
System.out.println("2 years ago it was: "
+ calndr.getTime());
}
}
輸出:
Current Date: Tue Feb 12 10:54:21 UTC 2019 After 50 days: Wed Apr 03 10:54:21 UTC 2019 6 months ago it was: Wed Oct 03 10:54:21 UTC 2018 2 years ago it was: Mon Oct 03 10:54:21 UTC 2016
示例2:
// Java Code to illustrate add() Method
import java.util.Calendar;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr
= Calendar.getInstance();
// Displaying the Current Date
System.out.println("Current Date: "
+ calndr.getTime());
// Adding 30 days to the
// Current Calendar
calndr.add(Calendar.DATE, 30);
System.out.println("After 30 days: "
+ calndr.getTime());
// Subtracting 3 months from
// the Current calendar
calndr.add(Calendar.MONTH, -3);
System.out.println("3 months ago it was: "
+ calndr.getTime());
// Subtracting 10 years from
// the Current calendar
calndr.add(Calendar.YEAR, -10);
System.out.println("10 years ago it was: "
+ calndr.getTime());
}
}
輸出:
Current Date: Tue Feb 12 10:54:24 UTC 2019 After 30 days: Thu Mar 14 10:54:24 UTC 2019 3 months ago it was: Fri Dec 14 10:54:24 UTC 2018 10 years ago it was: Sun Dec 14 10:54:24 UTC 2008
參考: https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html#add-int-int-
相關用法
- Java Calendar get()用法及代碼示例
- Java Calendar set()用法及代碼示例
- Java Calendar internalGet()用法及代碼示例
- Java Calendar isSet()用法及代碼示例
- Java Calendar getTimeZone()用法及代碼示例
- Java Calendar getInstance()用法及代碼示例
- Java Calendar getGreatestMinimum()用法及代碼示例
- Java Calendar getAvailableLocales()用法及代碼示例
- Java Calendar getDisplayName()用法及代碼示例
- Java Calendar getDisplayNames()用法及代碼示例
- Java Calendar getFirstDayOfWeek()用法及代碼示例
- Java Calendar getLeastMaximum()用法及代碼示例
- Java Calendar hashCode()用法及代碼示例
- Java Calendar getTime()用法及代碼示例
- Java Calendar roll()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Calendar add() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。