SWIFT:从文本字段到日期的格式不起作用

时间:2019-02-23 11:53:14

标签: swift date nsdateformatter dateformatter

我具有以下功能,我需要标签根据所选日期更新星期数。日期选择是由 UIDatePicker 选择的。

如果我写 print(pickedDate),我会得到UIDatePicker刚刚选择的日期,因此看起来工作正常。
但是,如果我 print(selectedDate),则得到nil,因此公式中的错误致命错误:在展开可选值时意外发现nil

这是我的代码:

func selectWeek () {

        let formatter = DateFormatter()

        let pickedDate = dateEntry.text
        let selectedDate = formatter.date(from: pickedDate!)


        if (weekTwoIntervalJan! ... weekThreeIntervalJan!).contains(selectedDate!) {
            weekNrLabel.text = "Week 3"
        }
        else if (weekThreeIntervalJan! ... weekFourIntervalJan!).contains(selectedDate!) {
            weekNrLabel.text = "Week 4"
        }


        else if (startDateFebDate! ... weekOneIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 1"
        }

        else if (weekOneIntervalFeb! ... weekTwoIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 2"
        }
        else if (weekTwoIntervalFeb! ... weekThreeIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 3"
        }
        else if (weekThreeIntervalFeb! ... weekFourIntervalFeb!).contains(selectedDate!) {
            weekNrLabel.text = "Week 4"
        }


        else {
            print("fail")



}

1 个答案:

答案 0 :(得分:-1)

您的UIDatePicker的名字是什么?

也许您想做(用您的datePicker的名称替换UIDatePicker

let selectedDate = datePicker.date