package nilpointer.net;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
System.out.println("Today: " + simpleDateFormat.format(today));
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
// Add 20 days
calendar.add(Calendar.DATE, 20);
System.out.println("Add 20 days: " + simpleDateFormat.format(calendar.getTime()));
// Subtract 10 days
calendar.add(Calendar.DATE, -10);
System.out.println("Subtract 10 days: " + simpleDateFormat.format(calendar.getTime()));
// Add 3 months
calendar.add(Calendar.MONTH, 3);
System.out.println("Add 3 months: " + simpleDateFormat.format(calendar.getTime()));
// Subtract 2 months
calendar.add(Calendar.MONTH, -2);
System.out.println("Subtract 2 months: " + simpleDateFormat.format(calendar.getTime()));
// Add 3 years
calendar.add(Calendar.YEAR, 3);
System.out.println("Add 3 years: " + simpleDateFormat.format(calendar.getTime()));
// Subtract 2 years
calendar.add(Calendar.YEAR, -2);
System.out.println("Subtract 2 years: " + simpleDateFormat.format(calendar.getTime()));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Today: 14/11/2021
Add 20 days: 04/12/2021
Subtract 10 days: 24/11/2021
Add 3 months: 24/02/2022
Subtract 2 months: 24/12/2021
Add 3 years: 24/12/2024
Subtract 2 years: 24/12/2022