0

I'm trying to get posts from Facebook by Alamofire using this request:

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!)
        }
    }

And when I'm trying to parse date it do something like this:

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

All this date is download from facebook api and all are the same. So how Can I make this work correctly?

droho
  • 61
  • 10
  • 1
    You need to use date format "yyyy-MM-dd'T'HH:mm:ssZ"...hh -> represents date in 12-hours format, HH -> represents date in 24-hours format – Mahendra Mar 29 '18 at 10:05

1 Answers1

1

your Time format is 24 hour so change the date format from

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

to

dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143