用textfield swift计算年龄4

时间:2018-04-22 10:47:04

标签: swift

我想计算一个在文本领域输入生日的年龄。

 @IBAction func profilSettings(_ sender: AnyObject) {
    var a = self.dob.text
    var c = a!.components(separatedBy: "-")
    var y1 = c[2]
    let cal = NSCalendar? = NSCalendar(calendarIdentifier: .gregorian)
    let now = Date()
    let year = Calendar.components(.year, from: dob!, to: now, options: [])
    let age = (year!) - Int(y1)!
    self.myage.text = String(age)        
}

错误:

  

无法分配类型" NSCalendar?.Type"的不可变表达式

     

对成员"组件(_:from :)和#34;

的模糊引用

2 个答案:

答案 0 :(得分:1)

在这里,您可以使用此代码从输入的日期字符串中获取年龄

/// DOB String Entered
let dob : String = "05-31-1996"

/// Format Date
var myFormatte = DateFormatter()
myFormatte.dateFormat = "MM-dd-yyyy"

/// Convert DOB to new Date
var finalDate : Date = myFormatte.date(from: dob)!

/// Todays Date
let now = Date()
/// Calender
let calendar = Calendar.current

/// Get age Components
let ageComponents = calendar.dateComponents([.year], from: finalDate, to: now)
print("Age is \(ageComponents.year!)") /// Output 21

输出屏幕截图

enter image description here

答案 1 :(得分:0)

两个问题:

  • 使用Calendar而不是NSCalendar

    let cal = Calendar:identifier: .gregorian)!
    
  • 发生错误,因为您使用的是Calendar类型而不是实例calCalendar的API是dateComponents(...

    let year = cal.dateComponents([.year], from: dob!, to: now)
    

还有更多问题:

  • dob必须是Date个实例,即生日。
  • let age = (year!) - Int(y1)!错误,预期结果为let age = year.year!