【问题标题】:Swift DateFormatter() doesn't format all date [duplicate]Swift DateFormatter() 不会格式化所有日期 [重复]
【发布时间】:2018-03-29 09:55:08
【问题描述】:

我正在尝试使用此请求通过 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 下载的,都是一样的。 那么我怎样才能使它正常工作呢?

【问题讨论】:

  • 你需要使用日期格式 "yyyy-MM-dd'T'HH:mm:ssZ"...hh -> 表示日期为12小时格式,HH -> 表示日期为24 -小时格式

标签: ios iphone swift alamofire


【解决方案1】:

您的时间格式是 24 小时,因此请更改日期格式

dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"

dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-08-16
    相关资源
    最近更新 更多