-3

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)
iOS.Lover
  • 5,923
  • 21
  • 90
  • 162
  • The error message has nothing to do with the conversion of the date. It looks like it's probably got something to do with the extract data not containing the key "date". What line is the app crashing on? – Fogmeister Jul 19 '16 at 09:31
  • In your *thought* date format where does the **T** come from? – vadian Jul 19 '16 at 09:37
  • @vadian : https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/ – iOS.Lover Jul 19 '16 at 09:37
  • 2
    Yes, of course, but in the Apple example there is a **T** in the source date string. There is no need to guess because the [documentation](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns) describes exactly the relationship between the date components and the placeholders. – vadian Jul 19 '16 at 09:41

1 Answers1

1

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)
fiks
  • 1,045
  • 9
  • 21