Parsing JSON (date) to Swift

后端 未结 3 808
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 22:33

I have a return JSON in my application in Swift, and have a field that returns me a date. When I refer to this data, the code gives me something like \"/ Date (1420420409680

3条回答
  •  -上瘾入骨i
    2020-12-09 23:00

    Adding onto what the others have provided, simply create utility method in your class below:

      func dateFromStringConverter(date: String)-> NSDate? {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()
        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" //or you can use "yyyy-MM-dd'T'HH:mm:ssX"
        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(date)!
    
        return dateFromString
    }
    

    Then you can call this method in your successfully returned, parsed JSON object, like below:

    //Parse the date
     guard let datePhotoWasTaken = itemDictionary["date_taken"] as? String else {return}
         YourClassModel.dateTakenProperty = self.dateFromStringConverter(datePhotoWasTaken)
    

    Or you can ignore the utility method and the caller code above entirely and simply do this:

    //Parse the date
     guard let datePhotoWasTaken = itemDictionary["date_taken"] as? NSString else {return}
         YourClassModel.dateTakenProperty = NSDate(timeIntervalSince1970: datePhotoWasTaken.doubleValue)
    

    And that should work!

提交回复
热议问题