Mc.Lover Mc.Lover - 4 months ago 20
iOS Question

Guess is the exact date format from a string

I am trying to guess the exact date format from a string :

2016-07-19 19:30:00 +0000


I think the default date format is :

yyyy-MM-dd'T'HH:mm:ssZZZZZ


but when I try to convert it to another date format I've got this error :

fatal error: unexpectedly found nil while unwrapping an Optional value


I think the date format is not match with my string ! Any help ?
Code :

let getDateEvent = String(extractData.valueForKey("date")!)
print(getDateEvent)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = dateFormatter.dateFromString(getDateEvent)

dateFormatter.dateFormat = "eeee, MMM d"///this is you want to convert format
let timeStamp = dateFormatter.stringFromDate(date!)
print(timeStamp)

Answer

The following format works as you would expect:

let getDateEvent = "2016-07-19 19:30:00 +0000"
print(getDateEvent)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzzz"
let date = dateFormatter.dateFromString(getDateEvent)

dateFormatter.dateFormat = "eeee, MMM d"///this is you want to convert format
let timeStamp = dateFormatter.stringFromDate(date!)
print(timeStamp)