首先,您需要为Java中的Calendar类导入以下软件包。
import java.util.Calendar;
创建一个Calendar对象并显示当前日期和时间。
Calendar calendar = Calendar.getInstance(); System.out.println("Current Date and Time = " + calendar.getTime());
现在,让我们使用calendar.add()方法和Calendar.WEEK_OF_YEAR常量减少周数。由于我们在此处递减,因此请设置为负值。
calendar.add(Calendar.WEEK_OF_YEAR, -2);
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); //减去2周 calendar.add(Calendar.WEEK_OF_YEAR, -2); System.out.println("Updated Date = " + calendar.getTime()); } }
输出结果
Current Date = Thu Nov 22 18:14:20 UTC 2018 Updated Date = Thu Nov 08 18:14:20 UTC 2018