我有来自网站的 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/