Search code examples
swift3nsdateformatter

how to convert array string to date swift 3


I have an array, calendarFromDateArr that is as follows:

["2017-10-30T07:41:00", "2017-10-30T11:23:00", "2017-10-30T11:48:00", "2017-11-10T00:00:00", "2017-11-13T19:43:00", "2017-12-01T00:00:00", "2017-12-31T00:00:00"]

I am using this code but dateObjects are nil.

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

print(dateObjects)

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

    print(dateObjects)
}

I am using this code also but data is nil.


Solution

  • Because you're dateFormat string is wrong, you don't have a zone in your date strings (the Z stands for the time zone: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)

    This example here works perfectly fine:

    let dates =  ["2017-10-30T07:41:00", "2017-10-30T11:23:00", "2017-10-30T11:48:00", "2017-11-10T00:00:00", "2017-11-13T19:43:00", "2017-12-01T00:00:00", "2017-12-31T00:00:00"]
    
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let dateObjects = dates.flatMap { dateFormatter.date(from: $0) }
    
    print(dateObjects)
    

    Output:

    [2017-10-30 07:41:00 +0000, 2017-10-30 11:23:00 +0000, 2017-10-30 11:48:00 +0000, 2017-11-10 00:00:00 +0000, 2017-11-13 19:43:00 +0000, 2017-12-01 00:00:00 +0000, 2017-12-31 00:00:00 +0000]