1. 程式人生 > >java根據生日計算年齡工具類

java根據生日計算年齡工具類

在開發中時常遇到要通過生日計算年齡的需求,這裡記錄一下

 private static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 當前時間

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

            if (birth.after(now)) {//如果傳入的時間,在當前時間的後面,返回0歲
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//相容性更強,異常後返回資料
           return 0;
        }
    }

呼叫

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date bithday = format.parse("1994-08-23 17:20:20");
        int age = getAgeByBirth(bithday);
        System.out.println(age);

轉自: