Alessandro
Alessandro

Reputation: 4100

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?

Upvotes: 0

Views: 92

Answers (2)

Rob
Rob

Reputation: 437702

The Z stands for Zulu (i.e. UTC/GMT). If you want to generate a date string in that format (GMT with Z qualifier), please refer to Apple's Technical Q&A #1480, which reminds us to specify both locale and timeZone:

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

Or in macOS 10.12 and iOS 10, you can do:

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];

And then you can do:

NSString *dateString = [formatter stringFromDate:[NSDate date]];

Upvotes: 0

Daniel Rinser
Daniel Rinser

Reputation: 8855

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.

Upvotes: 1

Related Questions