iOS (swift)根据身份证获取年龄

2016-08-30  本文已影响715人  rockyMJ

支持18位和15位身份证

//根据身份证获取出生日期
    func birthdayStrFromIdentityCard(numberStr: String) -> (String) {
        var year:String = ""
        var month:String
        var day:String
        //截取前14位
//        let fontNumber = (numberStr as NSString).substringWithRange(NSMakeRange(0, 14))
        //判断是18位身份证还是15位身份证
        if (numberStr as NSString).length == 18 {
            year = (numberStr as NSString).substringWithRange(NSMakeRange(6, 4))
            month = (numberStr as NSString).substringWithRange(NSMakeRange(10, 2))
            day = (numberStr as NSString).substringWithRange(NSMakeRange(12, 2))
            let result = "\(year)-\(month)-\(day)"
            print(result)
            return result
        }else{
            year = (numberStr as NSString).substringWithRange(NSMakeRange(6, 2))
            month = (numberStr as NSString).substringWithRange(NSMakeRange(8, 2))
            day = (numberStr as NSString).substringWithRange(NSMakeRange(10, 2))
            let result = "19\(year)-\(month)-\(day)"
            print(result)
            return result
        }
        
    }
    //根据出生日期计算年龄的方法
    func caculateAge(birthday: String) -> (Int){
//        var resultTag = ""
        //格式化日期
        let d_formatter = NSDateFormatter()
        d_formatter.dateFormat = "yyyy-MM-dd"
        let birthDay_date = d_formatter.dateFromString(birthday)
        // 出生日期转换 年月日
        if let tempBirthDay_date = birthDay_date {
            let birthdayDate = NSCalendar.currentCalendar().components([.Year,.Month,.Day], fromDate: tempBirthDay_date)
            let brithDateYear  = birthdayDate.year
            let brithDateDay   = birthdayDate.day
            let brithDateMonth = birthdayDate.month
            // 获取系统当前 年月日
            let currentDate = NSCalendar.currentCalendar().components([.Year,.Month,.Day], fromDate: NSDate())
            let currentDateYear  = currentDate.year
            let currentDateDay   = currentDate.day
            let currentDateMonth = currentDate.month
            // 计算年龄
            var iAge = currentDateYear - brithDateYear - 1;
            if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
                iAge += 1
            }
            return iAge
        }
//计算错误
        return 9999
    }
上一篇 下一篇

猜你喜欢

热点阅读