不要将所选日期打印成快速标签

时间:2015-11-15 08:00:50

标签: swift datepicker forced-unwrapping

好吧,我们有一个日期选择器计算应用程序,我想知道为什么选定的日期不是prtinting我的文字标签。这是我的代码

@IBAction func calculateDays(sender: UIButton) {

    if startDateTextField.text == "" || endDateTextField == "" {

        let alert2 = UIAlertController(title: "Oops!", message: "Please Select a Start Date!", preferredStyle: UIAlertControllerStyle.Alert)
        alert2.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert2, animated: true, completion: nil)


    }
    else {

        let start = String(startDateTextField.text)
        let end = String(endDateTextField.text)
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy"


        guard let startDate = dateFormatter.dateFromString(start), endDate = dateFormatter.dateFromString(end) else {
            // You don't have dates, show error(print("error"), do no nothing - your choice.
            return
        }



        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
        let secondNewString = "\(components.day) days"
        resultNumberOfDays.text = secondNewString

    }

}

如果我强行打开它作为测试它可以使用(显然这不安全)

 let startDate:NSDate = dateFormatter.dateFromString(start)!
 let endDate:NSDate = dateFormatter.dateFromString(end)!

有关如何获取计算日期的任何想法,或让我知道我在这里失踪的内容

感谢

0 个答案:

没有答案