Skip to content

日历

按日计算年龄

import java.util.Calendar;

    // 由出生日期计算年龄
    public static int getAgeByBirthday(int yearBirth, int monthBirth, int dayOfMonthBirth) {
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1; // 获取月份的时候要注意 +1
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        if (age < 0) {
            return 0;
        }
        return age;
    }

    public static void main(String[] args) {
        System.out.println("Today: " + Calendar.getInstance().getTime());  // Today: Mon Aug 27 17:10:02 CST 2018
        System.out.println("age: " + getAgeByBirthday(1988, 8, 23));       // age: 30
        System.out.println("age: " + getAgeByBirthday(1990, 8, 23));       // age: 28
        System.out.println("age: " + getAgeByBirthday(1991, 8, 23));       // age: 27
        System.out.println("age: " + getAgeByBirthday(2000, 8, 26));       // age: 18
        System.out.println("age: " + getAgeByBirthday(2000, 8, 27));       // age: 18
        System.out.println("age: " + getAgeByBirthday(2018, 8, 28));       // age: 0
        System.out.println("age: " + getAgeByBirthday(2019, 8, 23));       // age: 0
    }