我有一个数组,calendarFromDateArr
如下:
["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"]
我正在使用此代码,但dateObjects
为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)
}
我也在使用此代码,但数据为nil
。
答案 0 :(得分:0)
因为你的dateFormat字符串错误,你的日期字符串中没有区域(Z代表时区:http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)
这个例子非常合适:
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)
输出:
[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]