java根據身份證號或生日計算年齡

2021-09-20 05:48:30 字數 1288 閱讀 9434

最近的專案中需要根據身份證號來計算年齡。廢話少說,上**。

private static final int invalidage = -1;//非法的年齡,用於處理異常。

/** *根據身份證號碼計算年齡

* @param idnumber 考慮到了15位身份證,但不一定存在

*/public static int getagebyidnumber(string idnumber) else if (idnumber.length() == 18) else

******dateformat ******dateformat = new ******dateformat("yyyymmdd");

try catch (parseexception e)

}/**

*根據生日計算年齡

* @param datestr 這樣格式的生日 1990-01-01

*/public static int getagebydatestring(string datestr) catch (parseexception e)

}public static int getagebydate(date birthday)

int yearnow = calendar.get(calendar.year);

int monthnow = calendar.get(calendar.month);

int dayofmonthnow = calendar.get(calendar.day_of_month);

calendar.settime(birthday);

int yearbirthday = calendar.get(calendar.year);

int monthbirthday = calendar.get(calendar.month);

int dayofmonthbirthday = calendar.get(calendar.day_of_month);

int age = yearnow - yearbirthday;

if (monthnow <= monthbirthday && monthnow == monthbirthday && dayofmonthnow < dayofmonthbirthday || monthnow < monthbirthday)

return age;

}

有的人可能會問採用異常來處理非法年齡,我在這簡單說明,在工作中,我一般會盡量避免異常的發生,畢竟出現了崩潰不是什麼好事,特別是在android開發中。

java根據身份證號或生日計算年齡

private static final int invalidage 1 非法的年齡,用於處理異常。根據身份證號碼計算年齡 idnumber 考慮到了15位身份證,但不一定存在 public static int getagebyidnumber string idnumber else if i...

根據身份證號回填生日

根據身份證號回填生日 開發工具與關鍵技術 visual studio 2015在我們做的很多專案中,我們都可以看到很多賬號的註冊,而在我們註冊賬號的時候總是要填寫很多很多關於個人的一些資訊,而我們的身份證資訊以及生日這些資訊往往就是我們必填的選項,所以我們在填寫完我們的身份證資訊之後,如何讓我們的生...

mysql根據身份證號計算年齡

身份證號包含著出生日期,我們可以通過身份證號與當前日期來計算人的年齡。現有資料表 計算規則為先取出年份與當前年份作差,再比較當前日期與身份證上的月日 即判斷此人是否已經過了國曆生日 決定是否需要減去一歲,已經過了生日就不用減掉了。計算年齡的sql如下 an highlighted block sel...