UIDatePicker value does not match displayed date

790 views Asked by At

I encounter a weird issue if I set the maximum date of a UIDatePicker whenever I change the day on the UI, the value is always day - 1 I am doing something wrong ?

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
    }
}
1

There are 1 answers

0
Jakub Vano On BEST ANSWER

Time zone of your UIDatePicker is most likely different from the time zone of myFormatter() - you can set time zone for UIDatePicker with

datePicker.timeZone = NSTimeZone(name: "UTC")