Search code examples
iosswiftswift2uidatepicker

Swift NSDateFormatter how to get appropriate formate form DatePicker


I need to get this format form datePicker 2016-09-30T15:01.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm"
let dateString = dateFormatter.stringFromDate(datePicker.date)

I use this code below but it return:

2016-09-30

Solution

  • You need to quote the T in the format.

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
    

    Any literal text (but not punctuation) in a date format must be enclosed in single quotes to indicate that the text isn't a format specifier.