Search code examples
jsonswiftdatetimensdateformatter

Convert JSON string into Date time and compare swift


I Have two question : 1) I want to convert the JSON string into time . I am getting the JSON String but i am not able to convert it into Time. Following is my code :

HERE SHOULD BE YOUR JSON ["status": 200, "data": 15:55, "Message": In Time]

the "data" i am getting is in string want to convert the data into actual time

if let datetime = json["data"] as? String {
    print("on CLick of in_time BUtton : \(datetime)")
    let formattter = DateFormatter()
    formattter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    formattter.date(from: datetime)
    print("form : \(formattter)")
    print("Date : \(datetime)")
}

2) I Have a Grace time and I want to Compare it with the server time which i will get through json How i can Achieve it Please help !!! grace time is 10:30


Solution

  • You can use like:

     if let strResp = json["data"]{
            let strDate = "\(strResp!)" //15:55
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "HH:mm" // Pass any format here you want according to your date response
            let convDate = dateFormatter.date(from: strDate)
            print(convDate!)
        }