Why create Date from String only failed On Real ip

2019-08-20 04:53发布

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!

4条回答
Juvenile、少年°
2楼-- · 2019-08-20 05:01

you date format slightly wrong, please use the bellow example dateformat.

let dateString : String = "Tue May 23 23:19:41 +0800 2017"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss ZZZ yyyy"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
print(dateFormatter.date(from: dateString))
查看更多
贪生不怕死
3楼-- · 2019-08-20 05:04

from the app docs

When working with fixed format dates, such as RFC 3339, you set the dateFormat property to specify a format string. For most fixed formats, you should also set the locale property to a POSIX locale ("en_US_POSIX"), and set the timeZone property to UTC.

RFC 3339

In macOS 10.12 and later or iOS 10 and later, use the ISO8601DateFormatter class when working with ISO 8601 date representations.

wiki ISO 8601

For proper format, use Date Field Symbol Table

查看更多
Emotional °昔
4楼-- · 2019-08-20 05:07

I bet it's crashing on the next line, not on the line you've commented. You're force-unwrapping the result. That force-unwrap will crash with the exact error you are reporting if the date conversion fails.

I call the ! operator the "crash if nil" operator. You should not do that. You need to program defensively and return the optional, then write the calling code to handle the case where the conversion fails.

Others have already pointed out that date formatters depend on the locale of the device, and if it's different your conversion could fail. Force the formatter's locale to a known locale if you want to give it literal strings who's format doesn't vary based on country and language.

查看更多
神经病院院长
5楼-- · 2019-08-20 05:20

this link may solve your problem.....

Swift

formatter.locale = Locale(identifier: "en_US")
查看更多
登录 后发表回答