I keep getting the error 'Cannot convert value of type 'UITextField?' to expected argument type'Date'

时间:2017-11-08 22:11:37

标签: ios swift4

I am trying to get the persons "age" filled in a text field from user input birthdate (text field) and user Calendar.

    var startDate = birthDate
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-YYYY"
    let currentDate = Date()
    let userCalandar = Calendar.current
    let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
    var age = Calendar.current.dateComponents(components, from: startDate, to: currentDate) (error is here)

Thanks for your thoughts

Andrew

1 个答案:

答案 0 :(得分:0)

这应该可以胜任。

        let textInput = birthDate.text
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-YYYY"
        let startDate = dateFormatter.date(from: textInput!)
        let currentDate = Date()
        let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
        let age = Calendar.current.dateComponents(components, from: startDate!, to: currentDate)