zoukankan      html  css  js  c++  java
  • java计算年龄

    精确到天计算年龄

     public static int getAgeByCardId(String card) throws Exception {
            Integer len = card.length();
            if (len == CHINA_ID_MIN_LENGTH) {
                card = conver15CardTo18(card);
            }
            String birthDate = card.substring(6, 14);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
            Date date = sdf.parse(birthDate);  
            return calcAge(date);
        }
    
    
    
     /**
         * 由出生日期获得年龄  精确到天
         * @param birthDay
         * @return
         * @throws Exception
         */
        public static int calcAge(Date birthDay) throws Exception {  
            Calendar cal = Calendar.getInstance();  
            if (cal.before(birthDay)) {  
                throw new IllegalArgumentException("出生日期不能晚于当前日期");  
            }  
            int yearNow = cal.get(Calendar.YEAR);  
            int monthNow = cal.get(Calendar.MONTH);  
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);  
            cal.setTime(birthDay);  
      
            int yearBirth = cal.get(Calendar.YEAR);  
            int monthBirth = cal.get(Calendar.MONTH);  
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);  
      
            int age = yearNow - yearBirth;  
      
            if (monthNow <= monthBirth) {  
                if (monthNow == monthBirth) {  
                    if (dayOfMonthNow < dayOfMonthBirth) age--;  
                }else{  
                    age--;  
                }  
            }  
            return age;  
        }

    按年计算年龄

     /**
         * 根据身份编号获取年龄
         * 
         * @param idCard
         *            身份编号
         * @return 年龄
         */
        public static int getAgeByIdCard(String idCard) {
            int iAge = 0;
            if (idCard.length() == CHINA_ID_MIN_LENGTH) {
                idCard = conver15CardTo18(idCard);
            }
            String year = idCard.substring(6, 10);
            Calendar cal = Calendar.getInstance();
            int iCurrYear = cal.get(Calendar.YEAR);
            iAge = iCurrYear - Integer.valueOf(year);
            return iAge;
        }
  • 相关阅读:
    [ARC101C] Ribbons on Tree
    NOIP2020 模拟赛 B 组 Day6
    #10471. 「2020-10-02 提高模拟赛」灌溉 (water)
    #10470. 「2020-10-02 提高模拟赛」流水线 (line)
    一类巧妙利用利用失配树的序列DP
    学军中学csp-noip2020模拟5
    信号与槽-高级应用
    PyQt5中的布局管理-QSplitter
    PyQt5中的布局管理-嵌套布局
    信号与槽-入门应用
  • 原文地址:https://www.cnblogs.com/shihaiming/p/7592057.html
Copyright © 2011-2022 走看看