Java 日历 add()方法及实例
Calendar类中的 add()方法用于根据日历的规则,从给定的日历字段(int field)中增加或减少特定的时间(int amt)。
语法
public abstract void add(int field , int amt)
参数: 该方法需要两个参数。
要对其进行操作的日历字段。(整数类型)需要被减去的时间量。(整数类型)返回值: 该方法不返回任何值。
例1 :
// Java Program to Illustrate add() Method// of Calendar class // Importing required classesimport java.util.Calendar; // Main classpublic class CalendarClassDemo { // Main driver method public static void main(String args[]) { // Creating a Calendar class object Calendar calndr = Calendar.getInstance(); // Displaying the current date // using getTime() method System.out.println("Current Date: " + calndr.getTime()); // Adding 50 days to the // Current Calendar // using add() method calndr.add(Calendar.DATE, 50); // Displaying the date now using getTime() method System.out.println("After 50 days: " + calndr.getTime()); // Subtracting 6 months from // the Current calendar calndr.add(Calendar.MONTH, -6); // Displaying the date now using getTime() method System.out.println("6 months ago it was: " + calndr.getTime()); // Subtracting 2 year from // the Current calendar calndr.add(Calendar.YEAR, -2); // Displaying the date now using getTime() method System.out.println("2 years ago it was: " + calndr.getTime()); }}
输出
Current Date: Tue Feb 12 10:54:21 UTC 2019After 50 days: Wed Apr 03 10:54:21 UTC 20196 months ago it was: Wed Oct 03 10:54:21 UTC 20182 years ago it was: Mon Oct 03 10:54:21 UTC 2016
例2 :
// Java Program to Illustrate add() Method// of Calendar class // Importing required classesimport java.util.Calendar; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating a calendar object Calendar calndr = Calendar.getInstance(); // Displaying the current date // using getTime() method System.out.println("Current Date: " + calndr.getTime()); // Adding 30 days to the current calendar // using add() method calndr.add(Calendar.DATE, 30); // Printing the corresponding date System.out.println("After 30 days: " + calndr.getTime()); // Subtracting 3 months from the current calendar calndr.add(Calendar.MONTH, -3); // Printing the corresponding date System.out.println("3 months ago it was: " + calndr.getTime()); // Subtracting 10 years from // the Current calendar calndr.add(Calendar.YEAR, -10); // Printing the corresponding date System.out.println("10 years ago it was: " + calndr.getTime()); }}输出
Current Date: Tue Feb 12 10:54:24 UTC 2019After 30 days: Thu Mar 14 10:54:24 UTC 20193 months ago it was: Fri Dec 14 10:54:24 UTC 201810 years ago it was: Sun Dec 14 10:54:24 UTC 2008
