Quintin Balsdon Quintin Balsdon - 5 years ago 228
Swift Question

SWIFT: Convert a date with the format E, dd, MMM, y, KK:mma

I am trying to convert a date from a String to NSDate with the following code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "E, dd MMM yyyy, KK:mma"
date = dateFormatter.dateFromString(strDate)

I have also tried the following formats:

  1. EEE, dd MMM yyyy, hh:mma

  2. EEE, dd MMM yyyy, KK:mm

but the out put is always nil

Converted Tue, 12 Jan 2016, 7:30am to nil with the formatter E, dd MMM yyyy, KK:mma

I have also considered the follow StackOverflow posts:

  1. String to NSDate in Swift

  2. How can I convert string date to NSDate?

and I have been using this link as a reference for the date formats

Answer Source

The typical reason is that your device is not set to English language. Note that parsing strings like Tue or Jan is language specific. That means you have to make sure the formatter has a correct language set, e.g.:

dateFormatter.locale = NSLocale(localeIdentifier: "en")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download