When I get to the df.date() line below, the app crashes when a date with this format 2016-12-27 14:40:46 +0000
is used:
fatal error: unexpectedly found nil while unwrapping an Optional value
And I also see this:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I have strings that can be in this format
12/27/2016
but sometimes in this format
2016-12-27 14:40:46 +0000
Here is the code snippet that crashes on the above format:
let mydate = "12/27/2016" //this works but not the longer format
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy" //this is the format I want both dates to be in
newDate:Date = df.date(from: mydate)
How do I handle both formats using basically one function?
Check if the date string contains a slash and set the date format accordingly:
You can try an approach that is very clean in your code. You can add this extension:
then just try changing the formats array in the function to whatever formats you may need. Now just use your formatter like this:
I think the best way to do this is using two DateFormatters, one for iso8601 format and other for this short format.
(My code below uses an extension of DateFormatter, but you can use a method / helper / anything else with these two formatters).
Swift 3