NSDate Formatting

早过忘川 提交于 2019-12-10 21:25:45

问题


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


回答1:


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




回答2:


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.




回答3:


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!



来源:https://stackoverflow.com/questions/6399365/nsdate-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!