ios - 从json时间获取数据并快速格式化时间

标签 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"]}

最佳答案

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

关于ios - 从json时间获取数据并快速格式化时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947688/

相关文章:

ios - 修改UITableView首次显示后的样式

java - Volley JSONException : End of input at character 0 of

javascript - 如何有效地从 Pandas 数据框转移到 JSON

javascript - 使用键值获取对 JSON/JS 对象中任意(深层)嵌套节点的引用

iphone - 将路由器代码升级到 Alamofire 4.0 和 Swift 3

ios - WorldPay Apple Pay SDK 无法识别的选择器发送到实例

ios - 切换两个 View Controller ,后退功能不起作用

ios - 边框逐渐淡出的圆形 UIView

ios - Swift 4 : XCode 9 Beta: Static factory method in Objective-C produces a valid object in Debugger, 但代码中为 NIL

ios - 如何在 swift 中显示 UITabBarController