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()
}
}
答案 0 :(得分:0)
在Swift 3中,如果您使用Date
和Calendar
而不是NSDate
和NSCalendar
,则会更糟糕。
现在,如果您要将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
。