【问题标题】:Get data from json time and format time in swift快速从json时间和格式时间获取数据
【发布时间】:2017-08-29 20:15:30
【问题描述】:

我有来自网站的 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"]}

【问题讨论】:

标签: ios json swift


【解决方案1】:

如果要将接收到的数组中的时间与当前时间进行比较,则无需将日期转换为 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]]  {

【讨论】:

  • 感谢您的回答,但我需要转换为 12 小时,因为我需要使用为用户输入 ui
猜你喜欢
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 2015-08-20
  • 2015-10-01
  • 2020-08-16
相关资源
最近更新 更多