Alessandro Alessandro - 1 year ago 73
iOS Question

Generate NSDate of this type: 2015-04-27T10:45:52Z

I am trying to set the date to PayPal pre-approval key in the following way:

@"2015-04-27T10:45:52Z", @"startingDate",

This date works, however I don't know how to reproduce it in code terms. I tried doing:

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]];

but this doesn't work. What is the Z at the end of the date?

Answer Source

First, your date format is not correct. Second, for consistent results, you should always hard-code the en_US_POSIX locale (the date formatter defaults to the user's locale):

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];   
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

Alternatively, I've had positive experience with iso-8601-date-formatter. ISO 8601 is a surprisingly complex standard with lots of edge cases, and this library seems to be able to cope with most of them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download