简体   繁体   English

如何将UTC日期转换为NSDate?

[英]How to convert a UTC date to NSDate?

I have a string that is UTC and would like to convert it to an NSDate. 我有一个UTC的字符串,并希望将其转换为NSDate。

static NSDateFormatter* _twitter_dateFormatter;
[_twitter_dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[_twitter_dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
[_twitter_dateFormatter setLocale:_en_us_locale];

NSDate *d = [_twitter_dateFormatter dateFromString:sDate];

When I go through the debugger d is nil even though sDate is "2010-03-24T02:35:57Z" 当我通过调试器时,即使sDate是“2010-03-24T02:35:57Z”,d也是零

Not exactly sure what I'm doing wrong. 不完全确定我做错了什么。

Ditto on the need to alloc/init your NSDateFormatter object, but you have another problem too: your Date format string does not match the actual date you're giving it. 同样需要分配/初始化您的NSDateFormatter对象,但是您还有另一个问题:您的日期格式字符串与您提供它的实际日期不匹配。

"EEE MMM dd HH:mm:ss ZZZ yyyy"
- vs -
"2010-03-24T02:35:57Z"

That format string would match something like: 该格式字符串将匹配以下内容:

"Wed Mar 24 00:07:33 -0400 2010"

See the unicode standard for the meaning of the date format string. 有关日期格式字符串的含义,请参阅unicode标准

You aren't allocating or initialising your NSDateFormatter object. 您没有分配或初始化NSDateFormatter对象。

Try something like this: 尝试这样的事情:

NSDateFormatter* _twitter_dateFormatter = [[NSDateFormatter alloc] init];
[_twitter_dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[_twitter_dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
[_twitter_dateFormatter setLocale:_en_us_locale];

NSDate *d = [_twitter_dateFormatter dateFromString:sDate];
[_twitter_dateFormatter release];

It's also unclear why you are declaring _twitter_dateFormatter as a static. 还不清楚为什么要将_twitter_dateFormatter声明为静态。 If you are trying to avoid re-allocating it, make it an ivar of your class. 如果您试图避免重新分配它,请将它变成您班级的ivar。

Apple gives source code for Parsing an RFC 3339 date-time . Apple提供了解析RFC 3339日期时间的源代码。 If using ARC, you'll may want to adjust that source by removing the calls to 'autorelease'. 如果使用ARC,您可能希望通过删除对“autorelease”的调用来调整该源。

FYI, RFC 3339 is a subset of ISO 8601 with one deviation (negative zero offset is allowed in RFC 3339). 仅供参考, RFC 3339ISO 8601的子集,具有一个偏差 (RFC 3339中允许负零偏移)。 So Apple's code is killing two birds with one stone, handling the so-called 'Internet-style' RFC 3339 datetimes as well as simple datetimes of ISO 8601. 因此,Apple的代码一举两得,处理所谓的“互联网式”RFC 3339日期时间以及ISO 8601的简单日期时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM