javadatecalendar

Java Calendar issue with adding year


I am trying to add a year to date but which is giving the same date for different inputs. Input dates are 28/Feb/2020 and 29/Feb/2020 and output are the same for both of them as 28/Feb/2021. Please help me to find what is wrong here.

Update:

I expect as output as 28/Feb/2021 and 01/Mar/2021.

public static Date dateAdd(Date newDate, int field, int amount) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(newDate);
        aCalendar.add(field, amount);
        return aCalendar.getTime();
    }

    public static void main(String[] args) throws Exception {

        System.out.println(dateAdd(new SimpleDateFormat("dd/MM/yyyy").parse("28/02/2020"),Calendar.YEAR,1));
        System.out.println(dateAdd(new SimpleDateFormat("dd/MM/yyyy").parse("29/02/2020"),Calendar.YEAR,1));

        // Console output below

        //Sun Feb 28 00:00:00 IST 2021
        //Sun Feb 28 00:00:00 IST 2021
    }

Solution

  • After going through documentation of add and roll. It is clear that what you are looking for is to be found in roll not add.

    Further after some research on the topic I found that the given scenario is also to be business dependent and depends what do you want to do because the add and roll gives you the choice to choose either of these.

    I found this while searching for the similar problem I had.

    Coming back to your code following modification is needed

    aCalendar.roll(field, amount);
    

    Someone more expert here will be able to help clean up this answer. JavaDocs for me were not very clear for these so the following question has some interesting answers to it