Brett
Brett

Reputation: 12007

NSDateFormatter format displaying incorrect format

I have the date (as an NSString) of the format:

20120508T224500Z

I am trying to use NSDateFormatter to create an NSDate from the string:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddTHHmmssZ"];
NSDate *dateFromString = [[NSDate alloc] init];  

But this parses/formats the NSDate incorrectly.

I am trying to get the format:

4:45 PM 5/8/2012

How can I use the date formatter yyyyMMddTHHmmssZ to get this format?

Upvotes: 1

Views: 254

Answers (1)

zaph
zaph

Reputation: 112857

You must single quote the 'T' and 'Z' in the string: 20120508T224500Z

See unicode date formatting for formatting information.

Example:

NSString *dateString = @"20120508T224500Z";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd'T'HHmmss'Z'"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];  
NSLog(@"dateFromString: %@", dateFromString);

[dateFormatter setDateFormat:@"h:m a M/d/yyyy"];
NSString *newDataString = [dateFormatter stringFromDate:dateFromString];
NSLog(@"newDataString: %@", newDataString);

NSLog output:

dateFromString: 2012-05-09 02:45:00 +0000
newDataString: 10:45 PM 5/8/2012

Note that NSLog used the NSDate description method and displays the date/time in local time.
Use - (void)setTimeZone:(NSTimeZone *)tz to create the string in a different timezone.

Upvotes: 4

Related Questions