David Seek February 2016

Swift2: String to date, format it and back to string. Found nil

I have a date string: Sun, 07 Feb 2016 21:16:21 +0000

And need it in: dd.MM.yyyy

Following method throws fatal error: nil

if parsedElement == "date" {
    if currentArticle.date.isEmpty {

        let dateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
        let tempDate = dateFormatter.dateFromString(str)
        dateFormatter.dateFormat = "dd.MM.yyyy"
        let convertedDate = dateFormatter.stringFromDate(tempDate!)

        currentArticle.date = convertedDate

    }
}

Debug:

str String "Sun, 07 Feb 2016 21:16:21 +0000"

tempDate NSDate? 2016-02-07 21:16:21 UTC 0xe41bc67eba500000​

convertedDate String "07.02.2016"

Looks great, but the moment I release "currentArticle.date = convertedDate"​ it says convertedDate​ = nil

Ideas?

PS: currentArticle.date == isEmpty

EDIT: The if loop runs 5 times. If I give currentArticle.date = str (only the date string), this is what the debugger says:

1. str String "Sun, 07 Feb 2016 21:16:21 +0000"

2. str ""

3. str String "Thu, 04 Feb 2016 21:18:34 +0000"

4. str ""

5. str String "Thu, 04 Feb 2016 18:57:14 +0000"

Answers


Rajesh R February 2016

Problem might be within your dateformatter string..Try timezone with some other values. Like zzzz


Craig Grummitt February 2016

You're getting the fatal error:

unexpectedly found nil while unwrapping an Optional value -> tempDate

I assume you're getting this error in the line:

let convertedDate = dateFormatter.stringFromDate(tempDate!)

This is because you're force unwrapping an optional which is equal to nil. You should use optional binding to unwrap it, i.e.:

if let tempDate = tempDate {
    let convertedDate = dateFormatter.stringFromDate(tempDate)
    currentArticle.date = convertedDate
}

Now the question of why your date formatter is not returning a value for str in this instance is all to do with your data. You can add an else to the above optional binding code block to display str in this instance to narrow down the problem.

Post Status

Asked in February 2016
Viewed 3,473 times
Voted 6
Answered 2 times

Search




Leave an answer