Date Manipulation using Calendar class in Java

Please refer to the simple code below. I want to deduct one month from current month and expecting value of February 2015 in output.

    Calendar today = Calendar.getInstance();
    System.out.println(today.getTime().toString());

    today.set(Calendar.MONTH, -1);
    Date date = today.getTime();
    System.out.println(date.toString());

The program output is as below. I don't see the month February as expected, instead is shows Dec 2014 as month.

Tue Mar 31 11:48:34 EDT 2015

Wed Dec 31 11:48:34 EST 2014

Thanks for your time and help.

Jon Skeet
people
quotationmark

You're setting the month number to be -1, i.e. "December of the year before". You want to add -1 month:

today.add(Calendar.MONTH, -1);

I'd strongly recommend using Joda Time or Java 8's java.time package if you possibly can though - both are much nicer APIs than Date/Calendar.

people

See more on this question at Stackoverflow