JS根据身份证号码算年龄
生活随笔
收集整理的這篇文章主要介紹了
JS根据身份证号码算年龄
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果把身份證號碼傳到頁面上,在前端頁面獲取年齡就需要用到JS腳本了:
function GetAge(identityCard) {
var len = (identityCard + "").length;
if (len == 0) {
return 0;
} else {
if ((len != 15) && (len != 18))//身份證號碼只能為15位或18位其它不合法
{
return 0;
}
}
var strBirthday = "";
if (len == 18)//處理18位的身份證號碼從號碼中得到生日和性別代碼
{
strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
}
if (len == 15) {
strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
}
//時間字符串里,必須是“/”
var birthDate = new Date(strBirthday);
var nowDateTime = new Date();
var age = nowDateTime.getFullYear() - birthDate.getFullYear();
//再考慮月、天的因素;.getMonth()獲取的是從0開始的,這里進行比較,不需要加1
if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
作者:Eric Li
出處:http://www.cnblogs.com/ericli-ericli/
除轉載文章外,隨筆版權歸作者和博客園所有,歡迎轉載,轉載請標明出處。
如果您覺得本篇博文對您有所收獲,覺得作者還算用心,請點擊右下角的 [推薦],謝謝!
總結
以上是生活随笔為你收集整理的JS根据身份证号码算年龄的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android开发之fragment之r
- 下一篇: Android开发之代码开发部分字符串变