从json时间获取数据并在swift中格式化时间

时间:2017-08-29 20:15:30

标签: ios json swift

我在网站的json中列出了数据时间列表,因此我需要将时间从24小时转换为12小时并使用时间与当前时间进行比较

这是我的代码: -

 let task=URLSession.shared.dataTask(with: url!) {(data, response, err) in
        if err != nil{
         print("err")
        }else{
            do{
               let dataT=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

                if let prayTime = dataT?["times"] as? NSArray  {
                    if let fajerTT = prayTime[0] as? String {         
                      let timeFormat = DateFormatter()
                       timeFormat.dateFormat = "hh:mm"
                        let timeFajer=timeFormat.date(from: fajerTT)
                      print(fajerTT)
                       print("\(timeFajer))")
                   self.fajerT.text=timeFajer
                    }else {print("false")}
                 }

            }catch{print("Error")

                  }


             }
    }



    task.resume()

这来自json

["05:05","06:30","12:56","16:30","19:21","19:21","20:51"]}

1 个答案:

答案 0 :(得分:2)

如果您想将收到的数组中的时间与当前时间进行比较,则无需将日期转换为12小时格式。

获取日期组件并将其与当前日期进行比较。

基本上你的日期格式是错误的。由于时间是24小时格式,因此HH:mm

实施例

let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = "hh:mm a"
let calendar = Calendar.current
let now = Date()

let times = ["05:05","06:30","12:56","16:30","19:21","19:21","20:51"]
for time in times {
    let date = timeFormatter.date(from: time)!
    let components = calendar.dateComponents([.hour, .minute], from: date)
    let match = calendar.date(now, matchesComponents: components)
    print(match)
    let output = outputFormatter.string(from: date)
    print(output)
}

并且 - 像往常一样 - 不要在Swift中使用Foundation集合类型(NSArray / NSDictionary),使用本机类型并且永远不会传递选项.mutableContainers

   if let dataT = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
      let prayTime = dataT["times"] as? [[String:Any]]  {