2017-08-29 67 views
0

JSON时间和格式的时间数据我已经从网站的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

的可能的复制[ xcode swift am/pm time to 24 hours format](https://stackoverflow.com/questions/29321947/xcode-swift-am-pm-time-to-24-hour-format) – BennX

+0

此外:https:///stackoverflow.com/q/36096533/1804251 – BennX

+0

请检查此:https://stackoverflow.com/questions/34360941/convert-an-array-of-times-from-24hr-to-12-hr-in-swift –

回答

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

而且 - 像往常一样 - 不斯威夫特使用基金会收藏类型(NSArray/NSDictionary),使用本机的类型和永远传递选项.mutableContainers

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

谢谢你的答案,但我需要转换为12小时,因为我需要使用为用户输入ui –

+0

我更新了答案。 – vadian