Wednesday, December 21, 2011

How to add and subtract years, months and days using Calendar class

In Java the best option for you is using the Calendar object.
Calendar c = Calendar.getInstance();//Create Calendar instance
Date today = c.getTime();//Initially this returns today
System.out.println(today);

c.add(Calendar.YEAR, 10);//Add 10 years
c.add(Calendar.MONTH , 1);//Add a month
c.add(Calendar.DATE, 5);//Add 5 days
Date futureDay = c.getTime();
System.out.println(futureDay);

Note that when you are using the Calendar class you need not to bother about number of days the month contains, leap years etc.
Similarly in order to subtract 10years just use -10 as below
c.add(Calendar.YEAR, -10);//Subtract 10 years

No comments:

Post a Comment