天天看點

java calendar.add方法_java.util.Calendar add()方法

java.util.Calendar add()方法

java.util.Calendar.add() 此方法根據月曆的規則将指定的(帶符号的)時間量添加到給定的月曆字段中。

1 文法

public void add(int field,int amount)

2 參數

field:月曆字段。

amount:要添加到該字段的日期或時間的數量。

3 傳回值

4 示例1

package com.yiidian;

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

5 示例2

package com.yiidian;

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

6 示例3

package com.yiidian;

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

7 示例4

package com.yiidian;

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