在 Objective C 中转换日期格式
我如何转换以下日期“Sun Jul 17 07:48:34 +0000 2011” 为以下格式“2011-07-17 07:48:34”?
我使用了 NSDateFormatter
,如下所示,但它不起作用。它给出的结果为 null。
NSDateFormatter *objDateFormatter = [[NSDateFormatter alloc] init];
[objDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[objDateFormatter dateFromString:sDate];
How can i convert the following date "Sun Jul 17 07:48:34 +0000 2011"
to the following format "2011-07-17 07:48:34"?
I used NSDateFormatter
as shown below but it didnt work. It gives null as a result.
NSDateFormatter *objDateFormatter = [[NSDateFormatter alloc] init];
[objDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[objDateFormatter dateFromString:sDate];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于您传入的日期样式,您的日期格式错误。这是解释不同修饰符的文档:日期格式模式
要解析日期“Sun Jul 17 07:48:34 +0000 2011”,您需要这样的格式:
要将其放入以下格式:“2011-07-17 07:48:34”,完整代码如下:
You've got your Date Format wrong for the style of Date you are passing in. Here is a document explaining the different modifiers: Date Format Patterns
To parse the Date "Sun Jul 17 07:48:34 +0000 2011", you'd need a Format like so:
To get it into the following format: "2011-07-17 07:48:34", here is the full code:
如果 sDate 是格式为“Sun Jul 17 07:48:34 +0000 2011”的字符串,则必须将其转换为 NSDate。然后,您可以使用第二个 NSDateFormatter 将此日期转换为您所需的格式“yyyy-MM-dd HH:mm:ss”。
如果您需要找出需要转换的字符串,这个网站有一个很好的参考:
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
例如“Sun Jul 17 07:48:34 +0000 2011”可以解析为
作为一点建议,像“Jul”(应该是 7 月)这样的非标准日期可能会在这里产生问题。使用 strftime() 将所需部分转换为纯 C 语言会更快。
请参阅参考资料:http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst263.htm
然后,您可以将 unix 时间戳转换回 NSDate,
使用 C 进行日期/时间解析通常可以快 10 倍。 NSDateFormatter 是一只慢狗。
If sDate is your string that's in the format "Sun Jul 17 07:48:34 +0000 2011", you have to convert that into a NSDate. Then, you can use a second NSDateFormatter to convert this date into your desired format "yyyy-MM-dd HH:mm:ss".
If you need to figure out the string needed to convert, this site has a great reference:
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
e.g. "Sun Jul 17 07:48:34 +0000 2011" can be parsed with
As a bit of advice, non-standard dates like "Jul" (should be July) can make problems here. It's faster to just convert the needed parts in plain C, with strftime().
See the reference: http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst263.htm
You can then convert the unix timestamp back in a NSDate with
Using C for date/time parsing is usually up to 10x faster. NSDateFormatter is a slow dog.