John
John

Reputation: 33

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

Upvotes: 3

Views: 705

Answers (3)

Caborca87
Caborca87

Reputation: 187

You can also do the following:

NSDateFormatter has the properties: dateStyle & timeStyle

You can set these to NSDateFormatterNoStyle, NSDateFormatterShortStyle, NSDateFormatterMediumStyle, NSDateFormatterLongStyle, NSDateFormatterFullStyle

Once these are set you can use stringFromDate: to get a nicely formatted string.

Check out the documentation page for each style does to the time and date.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/c/tdef/NSDateFormatterStyle

Cheers!

Upvotes: 0

Dan Sandland
Dan Sandland

Reputation: 7193

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

Upvotes: 4

Sai
Sai

Reputation: 3957

Try replacing MM with MMM -- I dont have XCode handy to verify but typically "M" or "MM" will refer to numeric month. In your case since you have "Jun" you should try MMM.

Upvotes: 4

Related Questions