My below code is working fine.
I don't know why it crashes sometimes(Mostly on application launch. 1 case out of ~100).
extension Formatter {
static let enUSPOSIX: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")//
return formatter
}()
}
let dateFormatter = Formatter.enUSPOSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+hh:mm"
let date = dateFormatter.date(from: "2018-05-13T00:00:00+05:30")
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let calendar = Calendar.current
let dayComponent = calendar.component(.year, from: date!)//crashes here sometime
print(dayComponent)
Basically your date format is wrong. The time zone +05:30
is ZZZZZ
not +hh:mm
, please read unicode.org Date Format Patterns
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
Edit:
For this standard ISO8601 format I'd prefer ISO8601DateFormatter
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: "2018-05-13T00:00:00+05:30")
I had the same issue when testing on one of my applications
let dateFormatter = Formatter.enUSPOSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+hh:mm"
let date = dateFormatter.date(from: "2018-05-13T00:00:00+05:30")
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let calendar = Calendar.current
let dayComponent = calendar.component(.year, from: date!)
This is Crashing because the date object is nil so when fore unwrapping the date in dayComponent line this crashes. try this
let dateFormatter = Formatter.enUSPOSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+hh:mm"
if let date = dateFormatter.date(from: "2018-05-13T00:00:00+05:30"){
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let calendar = Calendar.current
let dayComponent = calendar.component(.year, from: date!)
}else{
dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss+hh:mm" // Date as 12 hour
if let date = dateFormatter.date(from: "2018-05-13T00:00:00+05:30"){
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let calendar = Calendar.current
let dayComponent = calendar.component(.year, from: date!)
} else{
print("Cannot format Date")
}
}
Today I met exactly the same problem. Application randomly crashes on production because of force unwrapping on open func date(from string: String) -> Date?
My code looked like this:
let creationDate: Date = {
let dateFormatter = DateFormatter()
return dateFormatter.date(from: "19-06-2018 14:00")!
}()
After my investigation I realized that crashes appear only on devices which have set 12h date format in device settings. In these cases 14:00
does not exist because it should be "2:00PM".
Simply change in code fix that problem:
let creationDate: Date = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: "19-06-2018 14:00")!
}()