Harold Ship Harold Ship - 5 months ago 29
Swift Question

Swift: formatting NSDictionary as JSON with specific date format

Is there a way in Swift to specify a specific date format for

NSDate
object?

For example, if I have an
NSDictionary
with
NSDate
objects, and would like this JSON:

{
"something": [{
"something_else": [{
"data": {
"total": 117,
"updateTime": "2016-06-07T05:26:52-0300",
"endTime": "2016-06-07T08:26:52-0300",
"startTime": "2016-06-06T08:26:52-0300",
"dayRangeBars": [{
"belowRange": 36,
"aboveRange": 5
}]
}
}]
}]
}


Does
NSJSONSerialization.dataWithJSONObject
have a way of specifying the date format?

Answer

You'll need to stringify the date your self

Example:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
Comments