0

I am trying to put in order the returned date string from webService but the code below has not been working;

static func ConvertTStringToDate(dateString: String!) -> NSDate!
{
//      2014-06-28T00:00:00
    var dateTime: Array<String> = dateString.componentsSeparatedByString("T")
    var dateThrougTime: String = dateTime[0] + dateTime[1]

    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    var convertedDate: NSDate = dateFormatter.dateFromString(dateThrougTime)!

    return convertedDate
}
serhanaksut
  • 634
  • 3
  • 8
  • 25
  • 1
    How has it not been working? Does it throw an error, not return the correct date, or something else? – Undo Oct 22 '14 at 14:06
  • "fatal error: unexpectedly found nil while unwrapping an Optional value" error occured on the line "var convertedDate: NSDate = dateFormatter.dateFromString(dateThrougTime)! " – serhanaksut Oct 22 '14 at 14:07
  • Oh god... is this the new "Convert NSDate to NSString" question? – Fogmeister Oct 22 '14 at 14:07
  • 1
    Yes, yes it is. This question has been asked about 92,847,291,276,482,934,645,828,927,467,483,923,927,264,749 times on Stack Overflow. You have the wrong format for the dateFormatter. Look at your string. Look at your format. They're not the same. Therefore the date will be nil. – Fogmeister Oct 22 '14 at 14:09
  • 1
    BTW, this date with `T` in it is a RFC 3339/ISO 8601 string representation of the date. See [Apple Technical Note #1480](https://developer.apple.com/library/ios/qa/qa1480/_index.html) for special considerations. Do not use `componentsSeparatedByString` like you have above, but instead use `NSDateFormatter` with `dateFormat` of `yyyy-MM-dd'T'HH:mm:ss`, with `timeZone` of `NSTimeZone(forSecondsFromGMT: 0)`, and, less obviously, `locale` of `NSLocale(localeIdentifier: "en_US_POSIX")`. – Rob Oct 22 '14 at 14:14
  • Thanks @Rob probably more useful than my comment :) – Fogmeister Oct 22 '14 at 14:17
  • Ok thank you for your answers, I will try your suggestions. – serhanaksut Oct 22 '14 at 14:18
  • @Fogmeister No worries. You are right that this has been asked and answered many times, but I'm a little more sympathetic to OP than usual because this is one of those questions that is a little hard to find the right answer unless you know what you're looking for (lol; a Catch 22). And there are so many bad answers to this question, too, that it's hard to sift through the all of the bad ones to find the answer that gets to the root of the issue, [TN1480](https://developer.apple.com/library/ios/qa/qa1480/_index.html). – Rob Oct 22 '14 at 14:27
  • @Rob you're right about the plethora of bad answers. It's akin to the "just disable AutoLayout" answers about animation. I might actually right a blog about getting between NSString and NSDate. Hmm... – Fogmeister Oct 22 '14 at 14:28

0 Answers0