如何将 JSON 响应添加小时数转换为 Swift 中的当前日期

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

我在控制台中得到 JSON 类似的响应

 JSON: {
result =     {

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

服务调用代码:

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

我需要将小时数添加到当前日期,因此显示为 Monday June, 28(今天是 6 月 26 日)。

我该怎么做?

返回的 JSON 值是可选字符串。

您从 order_arrives 得出的“48”值似乎是要添加到当前日期的小时数。

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

输出(截至今天,6 月 26 日):

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