NSDateFormatter - 从 Twitter JSON API 解析日期时遇到问题
我正在尝试使用 NSDateFormatter 将 Twitter API 结果中的字符串转换为 NSDate 对象。我发现 NSDateFormatter 只是返回我的机器的当前日期/时间。任何帮助将不胜感激!
这是进入我的函数的字符串的样子:
2010 年 12 月 11 日星期六 01:35:52 +0000
这是函数:
+(NSDate*)convertTwitterDateToNSDate:(NSString*)created_at
{
// Sat, 11 Dec 2010 01:35:52 +0000
static NSDateFormatter* df = nil;
df = [[NSDateFormatter alloc] init];
[df setTimeStyle:NSDateFormatterFullStyle];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, d LLL yyyy HH:mm:ss Z"];
NSDate* convertedDate = [df dateFromString:created_at];
[df release];
return convertedDate;
}
这是返回的日期:
2010-12-10 17:58:26 -0800
这恰好是我电脑现在的日期和时间。
*注意!*将内存管理从分配 DateFormater 时使用自动释放更改为在函数中显式释放。当在一个巨大的循环中调用它时,我发现它开始因自动释放而失败(我猜汽车部件释放得不够快),但将其更改为此解决了问题。
I'm trying to convert a string from a Twitter API result into an NSDate object using NSDateFormatter. What I'm finding is that the NSDateFormatter is just returning the current date/time of my machine instead. Any help would be greatly appreciated!
Here's what the string looks like coming into my function:
Sat, 11 Dec 2010 01:35:52 +0000
And here's the function:
+(NSDate*)convertTwitterDateToNSDate:(NSString*)created_at
{
// Sat, 11 Dec 2010 01:35:52 +0000
static NSDateFormatter* df = nil;
df = [[NSDateFormatter alloc] init];
[df setTimeStyle:NSDateFormatterFullStyle];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, d LLL yyyy HH:mm:ss Z"];
NSDate* convertedDate = [df dateFromString:created_at];
[df release];
return convertedDate;
}
And here's the date returned:
2010-12-10 17:58:26 -0800
Which happens to be the date and time of my computer right now.
*Note!* changed memory management from using an autorelease when allocating the DateFormater, to an explicit release in the function. When calling this in a giant loop, I found that it started failing with the autorelease (I'm guessing the auto part wasn't releasing fast enough), but changing it to this fixed the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为是对的。因为原始字符串位于+0000时区,而结果日期位于-0800时区。因此,如果您仔细观察它们,您会发现它们是同一时间。
当您打印像[日期描述]这样的日期时,它将以当地时区打印,我相信但时间是绝对的。由于 NSDate 仅包含秒,不包含日历,也不包含时区信息。
(打印的字符串是相对于本地时区的,但实际日期是绝对的)
I think is right. because the original string is in +0000 time zone and the result date is in -0800 time zone. So if you lookt at them carefully you will notice is the same time.
When you print a date like [date description] it will be printed in the local time zone, I believe but the time is absolute. Since NSDate contains only seconds and not calendars, not time zone info.
(printed string is relative to local time zone but the real date is absolute)