-5

My problem is try convert string to date and crash.My app is on App Store, and running on my device, but it crashes on some devices.I looked crashes log and see it,is getting crash when string to date.I don't understand why my device is working or some devices is working well but others is crash.

func toDate() -> Date {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+03:00" //Your date format
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00") //Current time zone
    //according to date format your date string
    guard let date = dateFormatter.date(from: self) else {
        fatalError()
    }
    return date
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Baran Gungor
  • 176
  • 8

2 Answers2

1

Two solutions:

  1. Add en_US_POSIX locale for a fixed format.
  2. Use ISO8601DateFormatter (iOS 8+), the benefit is no locale, no date format, no time zone.

    func toDate() -> Date? {
        let dateFormatter = ISO8601DateFormatter()
        return dateFormatter.date(from: self) 
    }
    

In any case return an optional, fatalError() in production environment causes pretty bad user experience.

vadian
  • 274,689
  • 30
  • 353
  • 361
-1

You'll be crashing because anytime you try to execute this method on a string that isn't a date in the defined string format the dateFormatter will return nil, and then your guard statement will call fatalerror()

Just return the output of the dateformatter and handle the optional at the call site.

func toDate() -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+03:00" 
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00") 
    return dateFormatter.date(from: self) 
}

You might also want to consider just using the default current locale timezone rather than specifying one?

flanker
  • 3,840
  • 1
  • 12
  • 20