UIDatePicker 值与显示的日期不匹配

UIDatePicker value does not match displayed date

如果我在 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
    }
}

您的 UIDatePicker 的时区很可能与 myFormatter() 的时区不同 - 您可以使用

UIDatePicker 设置时区
datePicker.timeZone = NSTimeZone(name: "UTC")