Swift - Custom UIDatePicker format

16,748

Solution 1

You Can't Customize your UIDatePicker, Because UIDatePickerMode have four Types of Mode.

public enum UIDatePickerMode : Int {
    case Time // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)
    case Date // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)
    case DateAndTime // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 | 6 | 53 | PM)
    case CountDownTimer // Displays hour and minute (e.g. 1 | 53)
}

You can display only one of the mode as above.

Solution 2

Here is the code to get the date in your desired format:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm"
let strDate = dateFormatter.stringFromDate(NSDate()) // You can pass your date here as a parameter to get in a desired format
print(strDate)

Solution 3

I've done like this http://sourcefreeze.com/ios-datepicker-tutorial-uidatepicker-using-swift/

 var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        var strDate = dateFormatter.stringFromDate(myDatePicker.date)
        self.selectedDate.text = strDate

So, you need "yyyy-MM-dd HH:mm"

Share:
16,748
Fabrice Froehly
Author by

Fabrice Froehly

Updated on June 19, 2022

Comments

  • Fabrice Froehly
    Fabrice Froehly about 2 years

    i'd like to change the format of my UIDatePicker so it can like that "Year Month Day Hour(24) Min"

    Is there any way to do that ???

    Thanks