Bob
Bob

Reputation: 8724

Swift convert string with specific format to NSDate

I would like to convert these two strings to NSDate.

1."2015-10-19T15:27:48.173754Z"

2."2015-10-19T15:27:31Z"

I tried using this function for format #1:

static func prepareDate(dateString: String)-> NSDate
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
    let date = dateFormatter.dateFromString(dateString)
    return date
}

But it always return nil. Can someone advice what is the problem?

Upvotes: 1

Views: 600

Answers (1)

Warren Burton
Warren Burton

Reputation: 17378

You need to quote the T with ' marks

func prepareDate(dateString: String)-> NSDate?
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.dateFromString(dateString)
    return date
}

Its parsing as part of the date magic formatters.

let test = "2015-10-19T15:27:31Z" -> "Oct 19, 2015, 4:27 PM"

Upvotes: 6

Related Questions