0

I have list array of data times in json from website so i need convert time from 24 hours system to 12 hours and use times to make Compared with current time

this my code :-

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

and this from json

["05:05","06:30","12:56","16:30","19:21","19:21","20:51"]}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Possible duplicate of [xcode swift am/pm time to 24 hour format](https://stackoverflow.com/questions/29321947/xcode-swift-am-pm-time-to-24-hour-format) – bemeyer Aug 29 '17 at 20:34
  • And in addition: https://stackoverflow.com/q/36096533/1804251 – bemeyer Aug 29 '17 at 20:36
  • Please check this : https://stackoverflow.com/questions/34360941/convert-an-array-of-times-from-24hr-to-12-hr-in-swift – Vini App Aug 29 '17 at 21:16

1 Answers1

2

If you want to compare the times in the received array with the current time you don't need to convert the dates to 12 hour format.

Get the date components and compare it with the current date.

Basically your date format is wrong. Since the times are in 24 hour format it's HH:mm.

Example

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

And – as usual – do not use Foundation collection types (NSArray/NSDictionary) in Swift, use native types and never pass the option .mutableContainers

   if let dataT = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
      let prayTime = dataT["times"] as? [[String:Any]]  {
vadian
  • 274,689
  • 30
  • 353
  • 361