1

I've written such extension for String :

extension String {
    var asDate : NSDate! {
        print(self)
        let styler = NSDateFormatter()
        styler.dateFormat = "dd MMM yyyy"
        print(styler.dateFromString(self))
        if let aStyler = styler.dateFromString(self) {
            return aStyler
        } else {
            return NSDate()
        }
    }
}

I've noticed that it only works when English language is set on the device. However, it doesn't work with Russian, for example. Why?

It takes a string, e.g. "10 Apr 2016", and it should convert this string to date. However, styler.dateFromString(self) is always nil when the language is not English. I've checked that self (the string that I want to convert) matches the unicode format. However, I don't understand why styler.dateFromString(self) always returns nil.

hnh
  • 13,957
  • 6
  • 30
  • 40
phbelov
  • 2,329
  • 3
  • 18
  • 15
  • What do you mean by "I've checked that [the string] matches the unicode format"? Does that string contain the actual Russian name for April? Or do you want to convert the English string in a Russian environment? – hnh Apr 08 '16 at 13:47
  • 1
    Probably because Apr is not russian? Please check this one, you can set the locale so that you wouldnt have a problem. . -> http://stackoverflow.com/a/6735644/767329 – Mihriban Minaz Apr 08 '16 at 13:51
  • The string is always in English, the format of date is "10 Apr 2016". By Unicode format I meant that the styler.dateFormat string value matches LDML (http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Patterns_AM_PM), so it's correct. – phbelov Apr 08 '16 at 13:52

1 Answers1

4

If not configured otherwise, NSDateFormatter uses the default locale to parse strings. If you switch your computer to Russian, it will expect Russian month names. 'Apr' is not Russian, hence it can't parse that string as a valid month.

If the string to parse is always English, you need to set the locale of the formatter to an English locale. Like so:

let df        = NSDateFormatter()
df.locale     = NSLocale(localeIdentifier: "en_US")
df.dateFormat = "dd MMM yyyy"
let date      = df.dateFromString("21 Apr 2016")
hnh
  • 13,957
  • 6
  • 30
  • 40