对于GregorianCalendar类,请导入以下包。
import java.util.GregorianCalendar;
首先,让我们显示当前日期和时间。
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); System.out.println("Current date: " + cal.getTime());
现在,修改日期。在这里,我们使用该add()
方法将月份增加了两天。
cal.add((GregorianCalendar.MONTH), 2);
import java.util.Calendar; import java.util.GregorianCalendar; public class Demo { public static void main(String[] a) { GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); System.out.println("Current date: " + cal.getTime()); cal.add((GregorianCalendar.MONTH), 2); System.out.println("Modified date: " + cal.getTime()); } }
输出结果
Current date: Mon Nov 19 17:52:55 UTC 2018 Modified date: Sat Jan 19 17:52:55 UTC