【问题标题】:Calculate age from birth date using textfield and NSDateComponents in Swift4使用 Swift4 中的文本字段和 NSDateComponents 从出生日期计算年龄
【发布时间】:2018-04-24 17:12:49
【问题描述】:

我正在尝试使用此函数从 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)

}

但我得到一个错误 cannot assign NSCalendar?.Type,但我不知道为什么会得到这个错误(这是我第一次编码)

【问题讨论】:

标签: swift


【解决方案1】:

您的代码中存在一些问题。首先是 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
}

【讨论】:

    【解决方案2】:
      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
      }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      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!
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多