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
    }

本站作者: rustfisher.com | rf.cs@foxmail.com
示例地址: AndroidTutorial Gitee, Tutorial Github | 反馈问题: -> Android issues - gitee
本文链接: https://www.an.rustfisher.com/java/calendar/Java-Calendar-use/ |-> 本站文章最近更新
一家之言,仅当抛砖引玉。如有错漏,还请指出。下方的广告链接内容与本站无关。如果喜欢本站的内容,也可 -> 点击请作者喝咖啡 ,谢谢支持服务器。