跳转至

日历

按日计算年龄

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
    }
本站说明

一起在知识的海洋里呛水吧。广告内容与本站无关。如果喜欢本站内容,欢迎投喂作者,谢谢支持服务器。如有疑问和建议,欢迎在下方评论~

📖AndroidTutorial 📚AndroidTutorial 🙋反馈问题 🔥最近更新 🍪投喂作者

Ads