How to add or substract days to current date using Java Calendar?

Lot of times we need to add or subtract the days from current date , in java.util.Calendar there is one more .add method using this we can add or subtract the days.


import java.util.Calendar;

public class AddSubstractDays {

public static void main(String[] args) {

Calendar calNow = Calendar.getInstance(); // Getting instance of Calendar
System.out.println("Printing Current date : " + (calNow.get(Calendar.MONTH) + 1)
+ "-"
+ calNow.get(Calendar.DATE)
+ "-"
+ calNow.get(Calendar.YEAR));



//Lets add 5 days to current day using add method.

calNow.add(Calendar.DATE, 5);

System.out.println("date after five days : " + (calNow.get(Calendar.MONTH) + 1)
+ "-"
+ calNow.get(Calendar.DATE)
+ "-"
+ calNow.get(Calendar.YEAR));

//Lets substract 10 days using add method
calNow = Calendar.getInstance();

calNow.add(Calendar.DATE, -10);

System.out.println("Substracting 10 days : " + (calNow.get(Calendar.MONTH) + 1)
+ "-"
+ calNow.get(Calendar.DATE)
+ "-"
+ calNow.get(Calendar.YEAR));

}
}


Output :
Printing Current date : 10-23-2010
date after five days : 10-28-2010
Substracting 10 days : 10-13-2010
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment