Junaid
Junaid

Reputation: 7860

Date skips a year in Calculating next Birthday date

I am using the following code to check the birthday of a person:

public class Test_Year {


    static int yearsInterval =1; 
    static int yearsSpecial =0; 
    static Date dateYearsReg; 


    public static void main(String[] args){
        yearsToNotify(2013, "0001-10-02");
    }


    public static void yearsToNotify(int yearsElapsedSinceBirth, String dateOfBirth){
        Date dt = Convert(d); 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(dt); 
        System.out.println(); 


        yearsSpecial = yearsInterval*(1+(years/yearsInterval)); 
        System.out.println(yearsSpecial); 
        cal.add(Calendar.YEAR, yearsSpecial);
        dateYearsReg = cal.getTime(); 
        System.out.println(dateYearsReg);
    }

    public static  Date Convert(String S){

        String dateStr = S;
        Date d1 = null ;

        try {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            d1 = f.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return d1; 
    }

}

Ideally the above should give me the next birthday and the year should be 2014, however I get the year as 2015. The system date being todays date that is first of October 2014. Any hints?

In the baove if I give a call like: yearsToNotify(41, "1972-10-17"); I get the correct values. Seems this is a problem with results when I use the year as 0001.

Upvotes: 0

Views: 171

Answers (1)

Matthew Clark
Matthew Clark

Reputation: 173

I believe the problem stems from this line

cal.add(Calendar.YEAR, yearsSpecial);

If we look at the javadoc for ADD we see it is this

public abstract void add(int field,
       int amount)

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

Instead you want to be using set:

cal.set(Calendar.YEAR, yearsSpecial);

Upvotes: 2

Related Questions