开发者

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 =开发者_StackOverflow中文版 [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


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


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜