Search code examples
swiftnsdateformatterfatal-error

app crashes in simulator not on device for converting date format


On Converting "2019-04-25 15:31:22" into date format "MMM dd yyyy, hh:mm", app crashes in simulator but works fine on device.

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

func convertToString (dateString: String, formatIn : String, formatOut : String) -> String {
    let dateFormater = DateFormatter()
    dateFormater.timeZone = (NSTimeZone(abbreviation: "IST")! as TimeZone)
    dateFormater.dateFormat = formatIn
    let date = dateFormater.date(from: dateString)
    dateFormater.timeZone = NSTimeZone.system
    dateFormater.dateFormat = formatOut
    let timeStr = dateFormater.string(from: date!)
    return timeStr
}

Printing description of timeStr:

expression produced error: error: Execution was interrupted, reason: Fatal error: Unexpectedly found nil while unwrapping an Optional value. The process has been returned to the state before expression evaluation.

Want to understand convertToString is properly code.

One service output response in formate of "yyyy-MM-dd hh:mm:ss" & another services response date formate is "yyyy-MM-dd'T'HH:mm:ss'Z'"

    let convertedFormat =  convertToString(dateString: lastTime, 
formatIn: "yyyy-MM-dd hh:mm:ss", formatOut: "MMM dd yyyy, hh:mm")

let convertedDate =  convertToString(dateString: headline.publishedAt!, formatIn: "yyyy-MM-dd'T'HH:mm:ss'Z'", formatOut: "MMMM dd yyyy, hh:mm")
cell.lbl_NewsDate?.text = convertedDate

I want to use common utility converter function to show resultant time in "MMM dd yyyy, hh:mm" example Apr 26 2019, 23:32

resultant time need to show based on "Indian Standard Time".


Solution

  • It seems, that you use incorrect date format "MMM dd yyyy, hh:mm" in:

    formatIn: String, formatOut: String
    

    Hours is "HH", but not "hh".