简体   繁体   中英

In Calendar add subtract in java

I trying to subtract 60 days from calender . sample code

   try {


        cal.set(2014,02,12);  //year,month,date
        cal.add(Calendar.DATE, -60);

        System.out.println("Year = " + cal.get(Calendar.YEAR));
        System.out.println("Month = " + (cal.get(Calendar.MONTH)));
        System.out.println("Day = " + cal.get(Calendar.DAY_OF_MONTH));
    } 
    catch (Exception e) {
        e.printStackTrace();
    }

The output is

Year = 2014
Month = 0
Day = 11

if the date is

cal.set(2014,01,12);  //year,month,date

output is fine :

Year = 2013
Month = 11
Day = 14

How to fix this issue ?

There is nothing wrong you are getting the January month, as months start from 0

month - the value used to set the MONTH calendar field. Month value is 0-based. eg, 0 for January.

So what you are getting is 11-January-2014

EDIT:-

Based on the comments below are the months representation:

  • January: 0
  • February: 1
  • March: 2
  • April: 3
  • May: 4
  • June: 5
  • July: 6
  • August: 7
  • September: 8
  • October: 9
  • November: 10
  • December: 11

So your date 2014, 02 ,12 actually represents 12- March -2014 and when you are deleting 60 days from it then it will take you to January, and so the year will not change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM