NSDate 格式化
我有一个日期字符串,如下所示:“Fri, 17 Jun 2011 19:20:51 PDT”,我需要将其解析为 NSDate
格式。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEE, d MM YYYY HH:mm:ss zzz"];
NSDate *date = [dateFormatter dateFromString:currentPubDate ];
[dateFormatter release];
该代码似乎不起作用,我不确定为什么。我已经研究过这个问题,但通过论坛等进行搜索,似乎找不到答案。我确实相信这是 dateFormatter
的问题。感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您错误地指定了
setDateFormat
字符串。您应该这样指定它:YYYY
仅用于某些工业和商业应用程序的“周日期”格式。它看起来像这样:YYYY-Www-D
,其中 2011-W1-3 相当于 2011 年第一周的第三天。Apple文档指出,使用
是一个常见的错误>YYYY
而不是yyyy
:固定格式You incorrectly specified your
setDateFormat
string. This is how you should have specified it: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 ofyyyy
: Fixed Formats尝试用 MMM 替换 MM ——我没有方便验证的 XCode,但通常“M”或“MM”指的是数字月份。就你而言,既然你有“Jun”,你应该尝试 MMM。
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.
您还可以执行以下操作:
NSDateFormatter
具有以下属性:dateStyle
&timeStyle
您可以将它们设置为
NSDateFormatterNoStyle
、NSDateFormatterShortStyle
、NSDateFormatterMediumStyle
、NSDateFormatterLongStyle
、< code>NSDateFormatterFullStyle设置完成后,您可以使用 stringFromDate: 来获取格式良好的字符串。
查看文档页面以了解每种样式的时间和日期。
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/c/tdef/NSDateFormatterStyle
干杯!
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!