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


Java Calendar add()用法及代码示例


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-



相关用法


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