我试图通过Alamofire使用此请求从Facebook获取帖子:
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON {response in
switch response.result{
case .success:
if let data = response.data{
do{
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]{
let post = Post(dict: json)
postList = post.data
for index in postList.indices{
if (postList[index].message != nil) {
formattedPostList.append(postList[index])
}
}
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"
for index in formattedPostList.indices{
if let date = dateFormat.date(from: formattedPostList[index].created_time!){
print("Date parsed to date \(String(describing: formattedPostList[index].created_time))")
formattedPostList[index].created_time = dateFormat.string(from: date)
print("Parse date to string \(date)")
}else{
print("Date don't parse to date \(String(describing: formattedPostList[index].created_time))")
}
}
handler(formattedPostList)
}
}catch let error{
print(error)
}
}
case .failure:
print(response.error!)
}
}
当我试图解析日期时,它会执行以下操作:
Date parsed to date Optional("2018-02-10T10:42:05+0000")
Parse date to string 2018-02-10 10:42:05 +0000
Date don't parse to date Optional("2018-01-05T15:31:38+0000")
Date don't parse to date Optional("2017-12-28T14:00:35+0000")
Date don't parse to date Optional("2017-11-30T13:04:29+0000")
Date don't parse to date Optional("2017-10-11T13:31:01+0000")
Date parsed to date Optional("2017-10-05T12:41:44+0000")
Parse date to string 2017-10-05 00:41:44 +0000
所有这些日期都是从facebook api下载的,所有都是一样的。 那么我怎样才能正常工作呢?
答案 0 :(得分:1)
您的时间格式为24小时,因此请更改日期格式
dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"
到
dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"