如果我在UI上更改日期时设置了UIDatePicker的最大日期,我会遇到一个奇怪的问题,值总是白天 - 1 我做错了什么?
class DateField: UITextField {
private let datePicker = UIDatePicker()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
datePicker.datePickerMode = .Date
datePicker.maximumDate = NSDate()
datePicker.addTarget(self, action: "updateBirthdate", forControlEvents: .ValueChanged)
inputView = datePicker
// inputAccessoryView stuff
}
func updateBirthdate() {
text = NSDateFormatter.myFormatter().stringFromDate(datePicker.date)
}
}
extension NSDateFormatter {
class func myFormatter() -> NSDateFormatter {
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
}
答案 0 :(得分:6)
UIDatePicker
的时区很可能与myFormatter()
的时区不同 - 您可以使用
UIDatePicker
的时区
datePicker.timeZone = NSTimeZone(name: "UTC")