Search code examples
javadatetimegregorian-calendar

Why GregorianCalendar method add() does not work?


I created a class which represent a possible user for a library system. At the moment of the creation of this instance i need to set two fields: signingUpDate and expirationDate, both are Gregorian Calendar.

signingUpDate is the date at the moment of the creation, and expirationDate is signingUpDate + 5 years.

public class User {

    private GregorianCalendar signingUpDate;
    private GregorianCalendar expirationDate;

    public User(){
        setSigningUpDate;
        setExpirationDate;
    }

    private void setExpirationDate() {
        this.expirationDate = new GregorianCalendar();
        expirationDate.add(GregorianCalendar.YEAR, 5);
    }

    private void setSigningUpDate() {
        this.signingUpDate=new GregorianCalendar();
    }

When I use the method add(), expirationDate doesn't change. I tried to debug and I noticed that the field areFieldsSet turns false. But I didn't understand the meaning of that field. Can someone help me?


Solution

  • A bug(?) of GregorianCalendar, you can call getTime to 'refresh' it after adding 5 year:

    signingUpDate.add(Calendar.YEAR, 5);
    signingUpDate.getTime();
    

    Another solution, use java.time package instead, for exmaple, java.time.LocalDate.