我正在尝试使用此函数计算Swift中生日日期的年龄:(想要在textField中写入并从标签中的VC传递此数据)
{
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,但我不知道为什么会出现这个错误(这是我的第一次编码)
答案 0 :(得分:2)
您的代码中存在一些问题。首先是Qi Hao已经提到的类型,第二个你传递dob是一个文本字段你和Calendar组件方法需要两个日期,所以你应该首先解析文本字段日期然后你可以从输入日期获得年组件差异现在:
游乐场测试
let dob = UITextField()
dob.text = "03-27-2002"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: dob.text!) {
let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year!
print(age) // 16
}
答案 1 :(得分:0)
func age(on baseDate: DateComponents) -> Int {
if baseDate.month > month {
return baseDate.year - year
}
if baseDate.month == month && baseDate.day >= day {
return baseDate.year - year
}
return baseDate.year - year - 1
}
答案 2 :(得分:0)
试试这个:
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}