Search code examples
swiftswift3nsdateformatter

How to convert an array of date strings to an array of date objects, Swift


Looked at similar SO questions and found that there are no answers in Swift, there are plenty of answers exclusively for date formatting but not in combination with iteration.

I have an array of date strings like the below:

let dateStrings = ["2016-12-22T08:00:00-08:00", "2016-12-22T08:15:00-08:00", "2016-12-22T08:30:00-08:00"]

I would like to convert them to an array of local dateObjects like the below

var dateObjects = [2016-12-22 21:30:00 +0530, 2016-12-22 21:45:00 +0530, 2016-12-22 22:00:00 +0530]

I've tried iterating through the array of date strings but I get this error :

"fatal error: unexpectedly found nil while unwrapping an Optional value"

So I tried with optional binding without success. Please advice where I could be going wrong.

var dateObjects = [Date]()
let dateFormatter = DateFormatter()
for date in dateStrings{
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    let dateObject = dateFormatter.date(from: date)
    self.dateObjects.append(dateObject!)  // ERROR LINE
}

When I try with optional binding its going through else statement printing "Unable to convert to date object"

for date in dateStrings{
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    if let dateObject = dateFormatter.date(from: date){
        self.dateObjects.append(dateObject!)  // ERROR LINE
    }
    else{
        print("Unable to convert to date object")
    }
}

Solution

  • In second case you are force wrapping non-optional value there is no need of that and you are writing self with dateObjects var that is not declare as a instance property, also you can simply use flatMap to reduce your code and create array of Date from array of String.

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let dateObjects = dateStrings.flatMap { dateFormatter.date(from: $0) }