日历文本标签不会更新

时间:2017-03-15 23:19:50

标签: ios swift3 nsdate nsdateformatter

    datePicker.addTarget(self, action: #selector(datePickerChanged(datePicker:)), for: UIControlEvents.valueChanged)

    dateFormat()

} //this works
func dateFormat() {
    let today = NSDate()
    let dateFormatter = DateFormatter()
    let short = DateFormatter.Style.short
    dateFormatter.dateStyle = short
    dateFormatter.dateFormat = "MM-dd-YYYY"
    let startDate = dateFormatter.string(from: datePicker.date)
    dateLbl.text = startDate

    //this works but datePicker date when moved will not update
    let thirtyDays = NSCalendar.current.date(byAdding: Calendar.Component.day,value: 30, to: today as Date)
    let tomorrowSixty = dateFormatter.string(from: thirtyDays!)
    sixtyDay.text = tomorrowSixty

}
func datePickerChanged(datePicker:UIDatePicker){
    dateFormat()

}

}

1 个答案:

答案 0 :(得分:0)

在Swift 3中,如果您使用DateCalendar而不是NSDateNSCalendar,则会更糟糕。

现在,如果您要将sixtyDay标签设置为datePicker日期30天之后的日期,则需要datePicker.date使用date(byAdding:)而不是今天的日期。

func dateFormat() {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"
    let startDate = dateFormatter.string(from: datePicker.date)
    dateLbl.text = startDate

    //this works but datePicker date when moved will not update
    let thirtyDays = Calendar.current.date(byAdding: .day, value: 30, to: datePicker.date)
    let tomorrowSixty = dateFormatter.string(from: thirtyDays!)
    sixtyDay.text = tomorrowSixty
}

func datePickerChanged(datePicker:UIDatePicker){
    dateFormat()
}

注意:如果您使用dateFormat设置DateFormatter,则无需使用dateStyle设置DateFormatter,而且正确的年份格式化程序为{ {1}}不是yyyy