DateFormatter in Swift 3

Question

So, I have some code in my playground:

extension String {
   func stringToDate(withFormat format:String) -> Date? {
      let df = DateFormatter()
      df.dateFormat = format

      return df.date(from: self) ?? nil
   }
}

struct Some { 
   let date:String
}

let some = Some(date: "Fri, 06 Jan 2017 04:36:17 +0000")

print(some.date.stringToDate(withFormat: "E, dd MMM yyyy HH:mm:ss Z") ?? "ooops")

And it's work's fine. I received the date that I expected - 2017-01-06 04:36:17 +0000 But in my app same code and same string with date does not work properly

Playground: Playground

APP:App


Show source
| date   | swift   | ios   | nsdateformatter   2017-01-06 15:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 15:01

    You possibly have different default locales in playground and in application.

    You can check it with print(df.locale).

    E.g. if you set locale to ru_RU:

    df.locale = Locale(identifier: "ru_RU")
    

    then your date will not be parsed.

    To have stable parsing result set locale to en_US_POSIX as @MartinR suggested.

◀ Go back