Anton
Anton

Reputation: 111

DateFormatter in Swift 3

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

Upvotes: 2

Views: 1952

Answers (1)

mixel
mixel

Reputation: 25836

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.

Upvotes: 2

Related Questions