WilliaGuy
WilliaGuy

Reputation: 207

Convert NSDate to JSON Date?

I need to post a NSDate object using HTTP post to parse.com.
I don't know how to convert it.

//1  nsdate
[params setObject:date forKey:kKeyDate];

//2 nsstring
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"yyyy-MM-dd T HH : mm : ss.SSSZ"];
 NSString *newString = [dateFormat stringFromDate:date];
 [params setObject:newString forKey:kKeyDate];

Params are serialized in the body of the Http request. I know that everything else I'm doing is correct because if I comment out adding the NSDate to the params, then it works.

Upvotes: 4

Views: 3239

Answers (3)

SwiftArchitect
SwiftArchitect

Reputation: 48514

According to the Parse.com documentation:

{
    "__type": "Date",
    "iso": "2011-08-21T18:02:52.249Z"
}

Obj-C

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSString *newString = [dateFormat stringFromDate:date];
[params setObject:newString forKey:kKeyDate];

Upvotes: 1

Denis Krivitski
Denis Krivitski

Reputation: 644

If you are using iOS 10.0 or above, use the ISO8601DateFormatter class.

Upvotes: 2

pradip kikani
pradip kikani

Reputation: 637

try this ..

NSDate *CurrentDate = [NSDate date];
NSDateFormatter *DATEFORMATER = [[NSDateFormatter alloc]init];
[DATEFORMATER setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"];
[DATEFORMATER setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *DATE_STRING = [DATEFORMATER stringFromDate:CurrentDate];

Upvotes: 4

Related Questions