Search code examples
iosnsstringnsdatensdateformatter

NSDate Formatting


I have a date string as follows: "Fri, 17 Jun 2011 19:20:51 PDT" which I need to parse into an NSDate format.

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
 [dateFormatter setDateFormat:@"EEE, d MM YYYY HH:mm:ss zzz"];
 NSDate *date = [dateFormatter dateFromString:currentPubDate ];
 [dateFormatter release];

The code doesn't appear to be working and I am not sure why. I have looked into the issue but searching through forums etc and can't seem to find an answer. I do believe it is an issue with the dateFormatter. Thanks for your help


Solution

  • You incorrectly specified your setDateFormat string. This is how you should have specified it:

    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"];
    

    YYYY is only used in the "Week date" format used for some industrial and commercial applications. It looks like this: YYYY-Www-D where 2011-W1-3 would equate to the third day of the first week of 2011.

    The Apple docs note that it is a common mistake to use YYYY instead of yyyy: Fixed Formats