日期在计算下一个生日日期中跳过一年

时间:2014-10-01 10:01:04

标签: java datetime

我使用以下代码检查一个人的生日:

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; 
    }

}

理想情况下,上面应该给我下一个生日,年份应该是2014年,但我得到2015年。系统日期是今天的日期,即2014年10月1日。任何提示?

如果我打电话,请拨打电话:yearsToNotify(41,“1972-10-17”);我得到了正确的值。当我将年份用作0001时,似乎这是结果的问题。

1 个答案:

答案 0 :(得分:2)

我认为问题源于这一行

cal.add(Calendar.YEAR, yearsSpecial);

如果我们查看ADD的javadoc,我们看到它就是这个

public abstract void add(int field,
       int amount)

根据日历的规则,将指定的时间量添加或减去指定的日历字段。例如,要从日历的当前时间减去5天,您可以通过调用:

来实现

相反,您希望使用set:

cal.set(Calendar.YEAR, yearsSpecial);
相关问题