Add or subtract months to current date using Calendar - Java Date Time

Java examples for Date Time:Calendar

Description

Add or subtract months to current date using Calendar

Demo Code


import java.util.Calendar;
 
public class Main {
 
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));
   /*from   w w  w  .  ja  va2 s.  co m*/
    //add months to current date using Calendar.add method
    now.add(Calendar.MONTH,10);
 
    System.out.println("date after 10 months : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));
 
   
    //subtract months from current date using Calendar.add method
    now = Calendar.getInstance();
    now.add(Calendar.MONTH, -5);
 
    System.out.println("date before 5 months : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));
   
  }
}

Result


Related Tutorials