为什么NSDateFormatter无法解析ISO 8601格式的日期 [英] Why NSDateFormatter can not parse date from ISO 8601 format

查看:120
本文介绍了为什么NSDateFormatter无法解析ISO 8601格式的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将ISO 8601时间戳转换为NSDate:如何处理UTC时间偏移?

我使用rails作为后端,默认日期输出是2008-12-29T00:27:42- 08:00

I use rails as backend, the default date output is 2008-12-29T00:27:42-08:00

但是在我的研究之后NSDateFormatter不能支持它,除了我将日期更改为2008-12-29T00:27:42-0800

But after my research NSDateFormatter can not support it, except I change date out to 2008-12-29T00:27:42-0800

以下是我用来解析ISO 8601日期的代码,但它不起作用

Here is the code I used to parse ISO 8601 date, but it's not work

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSLog(@"%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42-08:00"]);

任何想法?

推荐答案

问题在于最后的时区。

The problem is with the timezone on the end.

您需要将其设置为:GMT-0X:00或-0X00,小时和分钟之间没有分开。

You need to either have it as: GMT-0X:00 or as -0X00 with no separate between hours and minutes.

以下两种组合有效:

组合1 - 使用GMT格式(GMT-0X:00)和ZZZZ

Combo 1 - use GMT format (GMT-0X:00) and ZZZZ

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSLog(@"DATE FORMAT:%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42GMT-08:00"]);

组合2 - 使用RFC 822格式(-0X00)和ZZZ

Combo 2 - use RFC 822 format (-0X00) and ZZZ

dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSLog(@"DATE FORMAT:%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42-0800"]);

这篇关于为什么NSDateFormatter无法解析ISO 8601格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆