Add time to Calendar

Problem:

You need to add or subtract time from a calendar.

Solution:

There are two ways to perform date math with a Calendar, use add(int,int) or roll(int,int). Roll will increment or decrement the specified field until the maximum or minimum value is reached, and then it will begin again. Adding 13 months to the calendar with roll will not increment the year.

Add will bubble up such that adding 13 months to a Calendar will also increment the year. To get the current date and add 3 months:

Calendar c = Calendar.getInstance(Locale.GERMAN); System.out.println(c.getTime()); c.add(Calendar.MONTH, 3); System.out.println(c.getTime());

To get the current date and subtract 7 weeks:

Calendar c = Calendar.getInstance(Locale.GERMAN); System.out.println(c.getTime()); c.add(Calendar.WEEK_OF_MONTH, -7); System.out.println(c.getTime());