简体   繁体   中英

How to convert JSON response adding hours to current date in Swift

I am getting JSON response like this in console

 JSON: {
result =     {

 "product_marchant" =             {
            fname = Seller1;
            id = 2;
            lname = One1;
            "order_arrives" = 48;
        };
    }
    }

servicecall code:

fileprivate func serviceCall(){
let param = ["jsonrpc": "2.0",
             "params": ["product_id" : productID
    ]] as [String : Any]

APIReqeustManager.sharedInstance.serviceCall(param: param, vc: self, url: getUrl(of: .product_details), header: header) {(responseData) in
    if responseData.error != nil{
        print(responseData.error)
        self.view.makeToast(NSLocalizedString("Something went wrong!", comment: ""))
    }else{
        self.detailsDB = ProductDetailsData(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())
        
        let var date = detailsDB.result.product_marchant.product_marchant
        
        print("JSON value \(date)")
    }
}
}

0/p

JSON value  48

I need to add the number of hours to the current date, so is shown as Monday June, 28 (today is 26th June).

How do I do this?

The JSON value returned is an Optional String.

It looks like the '48' value that you derive from order_arrives is the number of hours to add to current date.

let hours = Int(detailsDB.result.product_marchant.product.marchant!) ?? 0

let calendar = Calendar.current
let today = Date()

let formatter = DateFormatter()
formatter.dateStyle = .full

if let date = calendar.date(byAdding: .hour, value: hours, to: today) {
    print("JSON Value: \(formatter.string(from: date))")
}

Output (as of today, 26th June):

"JSON Value: Monday, June 28, 2021\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM