【发布时间】:2011-01-01 10:23:02
【问题描述】:
有没有一种简单的方法可以将您从 twitter 获得的时间戳转换为 unix 时间或从现在开始的分钟数?我可以解析字符串并自己转换所有内容,但我希望有一种不需要的转换方法。下面是一个带时间戳的 created_at 元素示例。
2007 年 3 月 18 日星期日 06:42:26 +0000
【问题讨论】:
有没有一种简单的方法可以将您从 twitter 获得的时间戳转换为 unix 时间或从现在开始的分钟数?我可以解析字符串并自己转换所有内容,但我希望有一种不需要的转换方法。下面是一个带时间戳的 created_at 元素示例。
2007 年 3 月 18 日星期日 06:42:26 +0000
【问题讨论】:
向 Apple 提出功能请求,让他们知道您希望在 iPhone 上使用此功能。 NSDateFormatter 提供了一个传统的 init 方法,它接受一个布尔标志,表明您希望它解析自然语言,但它仅在 OS X 上可用。Wil Shipley 不久前在启发式和人为因素的背景下写了一篇关于此功能的interesting post。
Apple 似乎不太可能提供此功能,因为此注释将在 NSDateFormatter docs 中指出:
iPhone OS 注意:iPhone OS 支持 只有 10.4+ 的行为。 10.0风格 方法和格式字符串不是 在 iPhone 操作系统上可用。
换句话说,我认为你必须自己解析它。
【讨论】:
听起来你需要类似:ISO 8601 parser and unparser。
【讨论】:
您可以将 NSDateFormatter 与以下内容一起使用:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[usLocale release];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
// see http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
[dateFormatter setDateFormat: @"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:[currentDict objectForKey:@"created_at"]];
[dateFormatter release];
NSTimeInterval seconds = [date timeIntervalSince1970];
【讨论】:
我整天都在为此苦苦挣扎,但是这个帖子帮助我找到了解决方案。
这就是我将 Twitter“created_at”属性转换为 NSDATE 的方式;
NSDateFormatter *fromTwitter = [[NSDateFormatter alloc] init];
// here we set the DateFormat - note the quotes around +0000
[fromTwitter setDateFormat:@"EEE MMM dd HH:mm:ss '+0000' yyyy"];
// We need to set the locale to english - since the day- and month-names are in english
[fromTwitter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
NSString *dateString = [item objectForKey:@"created_at"];
NSDate *tweetedDate = [fromTwitter dateFromString:dateString];
我希望有人会觉得这很有帮助。
【讨论】: