Suprised it could compîle. date(from:) is an instance method, not a class method.
When you say it failed, what is the error log you get ? Or just get nil ?
1 of 1 people found this helpful
The sample code is
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "E MMM d yyyy HH:mm:ss Zzzz"
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
dateFormatterGet.timeZone = TimeZone(abbreviation: "UTC")
let date1: Date? = dateFormatterGet.date(from: "Mon Dec 31 2012 13:30:00 GMT+0530")
print(date1!) -> Fatal error: Unexpectedly found nil while unwrapping an Optional value:
Printing description of date1:
▿ some : 2001-01-01 00:00:00 +0000
- timeIntervalSinceReferenceDate : 6.94278977517907e-310
There is no logs generated.
Tried in xcode 11 GM swift sample project.
It (nearly) works with XCode 10.3 in playground, giving
2012-12-31 13:29:59 +0000
Could you test in XCode11 playground ?
First, I’m going to draw your attention to Unicode Technical Standard #35 Part 4 Dates. This is the definitive specification for how date format strings are intended to behave.
Specifically, look at the Date Field Symbol Table. The time zone specifier you’re using,
Zzzz, is not listed there at all. I’m going to presume that, by starting with an uppercase Z, your goal was to get
ZZZZ. In that case, compare the example listed there,
GMT-8:00, against your example,
GMT+0530. Note the absence of a colon. If you change your example to use
ZZZZand include a colon, the string parses as you expect.
Where are you getting this string from? It seems like the folks generating it should be including that colon. Alternatively, if you have to deal with the string as is, you could use a format string that contains the literal
ZZZtoken, that is,
E MMM d yyyy HH:mm:ss 'GMT'ZZZ.
Share and Enjoy
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
Format "E MMM d yyyy HH:mm:ss 'GMT'ZZZ" solved our problem.