从日期选择器Swift 3计算年龄

时间:2017-01-06 18:47:47

标签: ios swift swift3 datepicker

在我的下面的代码中,我已经实现了一个日期选择器作为我的文本域的子视图。我被困在这个功能上; ' verifyAge&#39 ;.函数中的if语句工作正常,并且当日期选择器日期高于或低于指定日期时将更改textField颜色。但它只适用于相应的年份但不适用于确切的一天。我试着搜索过去两天,但无法找到解决我确切问题的方法。

 class AgeConfirmViewController: UIViewController, UITextFieldDelegate   {

@IBOutlet weak var txtAgeConfirmation: UITextField!
let datePicker: UIDatePicker = UIDatePicker()

 override func viewDidLoad() {
    super.viewDidLoad()
    txtAgeConfirmation.delegate = self
    createDatePicker()
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
    txtAgeConfirmation.inputView = datePicker
    datePicker.addTarget(self, action: #selector(self.datePickerChanged(sender:)), for: .valueChanged)
 }



   func datePickerChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.timeStyle = .none
    formatter.dateStyle = .long
    txtAgeConfirmation.text = formatter.string(from: sender.date)
    verifyAge()
}


  func createDatePicker() {
    datePicker.datePickerMode = .date
    datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 0, to: Date())
}


 func verifyAge() {

    let dateOfBirth = datePicker.date
    let today = Date()
    let gregorian = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
    let age = gregorian?.components([.month, .day, .year], from: dateOfBirth, to: today, options:[])

      if (age?.year)! < 21 {


        txtAgeConfirmation.textColor = UIColor.red

    } else if (age?.year)! > 21 {

        txtAgeConfirmation.textColor = UIColor.black

    }
}

1 个答案:

答案 0 :(得分:4)

简单的解决方案,忽略daymonth

let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: dateOfBirth, to: Date())
let age = ageComponents.year!

txtAgeConfirmation.textColor = age < 21 ? .red : .black

或者如果你想忽略时间

let ageComponents = calendar.dateComponents([.year], from: calendar.startOfDay(for: dateOfBirth), to: calendar.startOfDay(for: Date()))

在Swift 3中,使用原生Calendar结构的问号和感叹号较少 year之后的年龄感叹号绝对安全,因为明确指定了year组件。