Java教程

Java Calendar add()方法

此方法根据日历的规则将指定的(带符号)时间添加到给定的日历字段中。

语法

public void add(int field,int amount)

参数

field-日历字段。
amount-要添加到该字段的日期或时间的数量。

返回

此方法不返回值

抛出

IllegalArgumentException -如果字段是ZONE_OFFSET,DST_OFFSET或未知,或者在非宽容模式下任何日历字段的值超出范围。

示例1

import java.util.Calendar;
public class CalendaraddExample1 {
    public static void main(String[] args) {
        // create a new calendar
      Calendar cal = (Calendar) Calendar.getInstance();
        // print the current date and time
      System.out.println("" + cal.getTime());
        // add 9 years
      cal.add((Calendar.YEAR), 9);
        // print the modified date and time
      System.out.println("" + cal.getTime());
    }
}
输出:
Sun Jul 29 07:42:05 PDT 2018
Thu Jul 29 07:42:05 PDT 2027

示例2

import java.util.Calendar;
import java.util.*;
public class CalanderaddExample2 {
    public static void main(String[] args) {
        // create a new calendar
      Calendar cal = (Calendar) Calendar.getInstance();
        // print the current date and time
      System.out.println("" + cal.getTime());
        // add 2 months
      cal.add((Calendar.MONTH), 2);
        // print the modified date and time
      System.out.println("" + cal.getTime());
    }
}
输出:
Sun Jul 29 07:43:38 PDT 2018
Sat Sep 29 07:43:38 PDT 2018

示例3

import java.util.Calendar;
public class CalendaraddExample3 {
    public static void main(String[] args){
        // create a new calendar
      Calendar cal = (Calendar) Calendar.getInstance();
        // print the current date and time
      System.out.println("" + cal.getTime());
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DAY_OF_MONTH, 10);
        // print the modified date and time
      System.out.println("" + cal.getTime());
    }
}
输出:
Sun Jul 29 07:44:56 PDT 2018
Wed Aug 08 07:44:56 PDT 2018

示例4

import java.util.Calendar;
public class CalendaraddExample4 {
    public static void main(String[] args){
        // create a new calendar
     Calendar cal = (Calendar) Calendar.getInstance();
        // print the current date and time
      System.out.println("" + cal.getTime());
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.HOUR, 10);
        // print the modified date and time
      System.out.println("" + cal.getTime());
        cal.add(Calendar.MINUTE, 10);
        System.out.println("" + cal.getTime());
        cal.add(Calendar.SECOND, 10);
        System.out.println("" + cal.getTime());
    }
}
输出:
Sun Jul 29 07:46:00 PDT 2018
Sun Jul 29 17:46:00 PDT 2018
Sun Jul 29 17:56:00 PDT 2018
Sun Jul 29 17:56:10 PDT 2018
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4