计算生日

别bb上代码

public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date bithday = format.parse("2000-05-05");

        Calendar now = Calendar.getInstance();
        now.setTime(new Date());

        Calendar birth = Calendar.getInstance();
        birth.setTime(bithday);

        //计算两个时间相差多少年,需要-1因为还需要判断一下日期
        int res = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR) - 1;

        //如果已过生日则+1
        if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)){
            res += 1;
        }

        System.out.println(res);
    }

结果:

19

以上

你可能感兴趣的:(计算生日)