对于GregorianCalendar类,请导入以下包。
import java.util.GregorianCalendar;
创建一个对象。
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
现在,使用add()
带有负一(-1)的以下字段和方法来显示上个月。
cal.add((GregorianCalendar.MONTH), -1)
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), -1); System.out.println("Modified date (Previous Month): " + cal.getTime()); } }
输出结果
Current date: Mon Nov 19 18:07:03 UTC 2018 Modified date (Previous Month): Fri Oct 19 18:07:03 UTC 2018