Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Adding or Subtracting Months to Current date in Java

  1. import java.util.Calendar;
  2. public class Months {
  3. public static void main(String[] args) {
  4. //create Calendar instance
  5. Calendar now = Calendar.getInstance();
  6. System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
  7. + "-"
  8. + now.get(Calendar.DATE)
  9. + "-"
  10. + now.get(Calendar.YEAR));
  11. //add months to current date using Calendar.add method
  12. now.add(Calendar.MONTH,10);
  13. System.out.println("date after 10 months : " + (now.get(Calendar.MONTH) + 1)
  14. + "-"
  15. + now.get(Calendar.DATE)
  16. + "-"
  17. + now.get(Calendar.YEAR));
  18. //substract months from current date using Calendar.add method
  19. now = Calendar.getInstance();
  20. now.add(Calendar.MONTH, -5);
  21. System.out.println("date before 5 months : " + (now.get(Calendar.MONTH) + 1)
  22. + "-"
  23. + now.get(Calendar.DATE)
  24. + "-"
  25. + now.get(Calendar.YEAR));
  26. }
  27. }