2

Within our iphone app we parse a date gotten from an api call. The date returns correctly and is a valid date. Now only on some devices does it crash with the error of unexpectedly found nil while unwrapping an Optional value. Here is the code in question:

//formatDate(date: date, format: FullDateFormat)
class func formatDate(date: String, format: String)->String{
    if date.characters.count == 0 {return "" }
    let formatter = DateFormatter()
    formatter.dateFormat = Constants.FullDateFormat
    let nsDate = formatter.date(from: date)

    formatter.dateFormat = format
    return formatter.string(from: nsDate!)
}

nsDate is not being formatted as it is nil.

The Constants.FullDateFormat is a static string defined as "M/d/yyyy h:mm:ss a" as the date will always come in this format

The call to the class function will look like this

let newDate = Helpers.formatDate(date: "9/27/2017 9:26:51 AM", format: "h:mm a")

Some devices crash while majority don't. If we don't use the class function the app works correctly. I don't see any cause for it so if anyone sees why this may be happening and a possible solution, please let me know.

This may be a duplicate but didn't show up in any of the searches I performed. Thanks to community they pointed to another similar questions with answers already at stackoverflow. My apologies if this is a duplicate.

Micah Montoya
  • 757
  • 1
  • 8
  • 24
  • You should not use forced unwrapping of `nsDate`, you should put it in a guard statement. Most probably on the devices where your app crashes, some other settings (for example the locale) are different and those cause the issue with parsing dates, since you don't specify quite a bit of information used by `DateFormatter` – Dávid Pásztor Jun 29 '17 at 14:36
  • Thanks Martin R. I didn't see such when I did a search. I don't mind deleting this but it may help others. I'll though edit and point to the question you posted. – Micah Montoya Jun 29 '17 at 14:46
  • Solution is same as "Martin R" suggested but I understand Micah's confusion. – kulss Feb 20 '18 at 06:36

1 Answers1

7

It is a matter of locales. DateFormatter is dependent on the device's current location settings, including date and time.

You can ensure that the formatter's locale is always static by setting its locale to en_US_POSIX:

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

See Apple's link for more details:

https://developer.apple.com/documentation/foundation/nsdateformatter

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223