Search code examples
iosobjective-cswiftnsdatensdateformatter

Why create Date from String only failed On Real iphone?


I'm using following function to create Date from String. It works well on simulator. But it crashed on real iPhone.

String: "Tue May 23 23:19:41 +0800 2017"

The first picture is debugging information on real iPhone. The second one is debugging information on simulator. Debugging information on real iPhone

Debugging infomation on simulator

func createDate(fromString string: String) -> Date {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        let date = formatter.date(from: string) //fatal error: unexpectedly found nil while unwrapping an Optional value

        return date!
}

I even tried it on playground. It's really weird! Thanks!


Solution

  • this link may solve your problem.....

    Swift

    formatter.locale = Locale(identifier: "en_US")