Java Calendar arithmetic example: add day, add month 

Joined:
04/09/2007
Posts:
710

February 03, 2010 03:29:42    Last update: February 03, 2010 03:31:02
You can use the java.util.Calendar.add method to do date arithmetics. All calculations are straigntforward except for adding or subtracting months.
import java.text.*;
import static java.util.Calendar.*;

public class TestCalendar {
    private static final DateFormat FORMAT = new SimpleDateFormat("MM/dd/yyyy");

    public static void main(String[] args) throws Exception {
        Calendar c = Calendar.getInstance();
        c.set(DAY_OF_MONTH, 1);
        System.out.println("Initial Date: " + FORMAT.format(c.getTime()));

        c.add(DAY_OF_MONTH, -1);
        System.out.println("One Day Ago: " + FORMAT.format(c.getTime()));

        c.add(MONTH, 1);
        System.out.println("One Month Later: " + FORMAT.format(c.getTime()));

        c.add(MONTH, 1);
        System.out.println("Another Month Later: " + FORMAT.format(c.getTime()));
    }
}


The output is:
C:\>java TestCalendar
Initial Date: 02/01/2010
One Day Ago: 01/31/2010
One Month Later: 02/28/2010
Another Month Later: 03/28/2010


You started from January month end, advancing two months, you are no longer at month end. Use this trick to advance from onth end to month end:
// initialize calendar at previous month end
Calendar c = Calendar.getInstance();
c.set(DAY_OF_MONTH, 1);
c.add(DAY_OF_MONTH, -1);

// advance to the next month end
c.add(DAY_OF_MONTH, 1);
c.add(MONTH, 1);
c.add(DAY_OF_MONTH, -1);
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com