tags:

views:

185

answers:

2

I want to add days to a date to get a new date in Java. How to achieve it using the Calender class.

Calender dom = new GregorianCalender(d, m y);

is the instance of my date of manufacture and I want to reach to date of expiry adding some 100 days to the current date and store it in doe but unable to do that.

Any help would be appreciable.

+6  A: 

Make use of Calendar#add(). Here's a kickoff example.

Calendar dom = Calendar.getInstance();
dom.clear();
dom.set(y, m, d); // Note: month is zero based! Substract with 1 if needed.
Calendar expire = (Calendar) dom.clone();
expire.add(Calendar.DATE, 100);

If you want more flexibility and less verbose code, I'd recommend JodaTime though.

DateTime dom = new DateTime(y, m, d, 0, 0, 0, 0);
DateTime expire = dom.plusDays(100);
BalusC
thanks a ton. But when I try to make new instance of calenar with added value as new date it is not storing it in new instance.
terrific
You shouldn't do `new GregorianCalendar(d, m, y)`. Follow the same steps as here above. That's the only right way. Besides, note that you should put `y, m, d` in and not `d, m, y`. Also note that the month is zero based. January is 0, February is 1, March is 2, etc. It's a nightmare, the `Calendar`.
BalusC
Quick question - Why do you recommend against new GregorianCalendar(...)?
Everyone
Two reasons: 1) It's a better practice to program to the interface/abstract class. 2) You really need to `clear()` the calendar to avoid clashes sooner or later when cloning/comparing/etc.
BalusC
A: 

When using standard Java-API BalusCs answer is fine. If you use a lot of date computation it may worth the time to take a look on Joda Time. Which provides a (from mine point of view) better date handling. It also will be the base for the upcomming new Java Date API

GandalfIX
Didn't you note that I already suggested that and even posted a code example of it?
BalusC