Search code examples
iosswiftnsdateformatter

NSDateFormatter "dateFromString" returning nil


I'm trying to get the date from string "07:00 PM" using below code but its returning me nil always. Any help?

let hr12Formatter : NSDateFormatter = NSDateFormatter()
hr12Formatter.dateStyle = NSDateFormatterStyle.NoStyle
hr12Formatter.timeStyle = NSDateFormatterStyle.ShortStyle

hr12Formatter.dateFormat = "hh:mm a"
let hr12Date : NSDate = hr12Formatter.dateFromString(inputTimeString)!

Solution

  • Just remove those two lines date and time style, keep the dateFormat and set your date formatter locale to en_US_POSIX

    Swift 3 or later

    let formatter = DateFormatter()
    formatter.defaultDate = Calendar.current.startOfDay(for: Date())  // add this if you would like to use todays date as default
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "hh:mm a"
    let inputTimeString = "07:00 PM"
    if let hr12Date = formatter.date(from: inputTimeString) {
        print(hr12Date.description(with: .current))
    }