计算生日

2019-09-30  本文已影响0人  游荡w

别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

以上

上一篇 下一篇

猜你喜欢

热点阅读