YouTube API以RFC3339格式返回日期字符串。
Youtube API returns date string in RFC3339 format. I found how to parse it on manual, anyway, this is too long.
- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString // Returns a user-visible date time string that corresponds to the // specified RFC 3339 date time string. Note that this does not handle // all possible RFC 3339 date time strings, just one of the most common // styles. { NSString * userVisibleDateTimeString; NSDateFormatter * rfc3339DateFormatter; NSLocale * enUSPOSIXLocale; NSDate * date; NSDateFormatter * userVisibleDateFormatter; userVisibleDateTimeString = nil; // Convert the RFC 3339 date time string to an NSDate. rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease]; enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; [rfc3339DateFormatter setLocale:enUSPOSIXLocale]; [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString]; if (date != nil) { // Convert the NSDate to a user-visible date string. userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; assert(userVisibleDateFormatter != nil); [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle]; [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle]; userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date]; } return userVisibleDateTimeString; }我可以让一个函数包含这个,但我想知道是有pre在Cocoa基础或标准C或POSIX库中定义方式来做到这一点。我想使用它,如果它是。你能让我知道有更简单的方法吗?或者如果你确认这是最简单的方法将非常感谢:)
I can make a function contains this, but I want to know is there pre-defined way on Cocoa foundations or standard C or POSIX library to do this. And I want to use it if there it is. Can you let me know is there more simpler way? Or It will be very appreciate if you confirm this is most simple way :)
推荐答案您需要两种格式,因为小数秒是可选的,而时区应该是Z5,而不是Z.所以你创建两个格式化的格式
You need two formats because fractional seconds are optional, and the timezone should be Z5, not Z. So you create two formatters with formats
@"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5" @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5"并尝试两者。这显然是RFC3339;您的字符串可能不是该格式。很高兴你没有要求RFC822这是一个痛苦,做正确。但你应该真的有一个方法,返回NSDate,因为大多数用途实际上不需要为用户格式化的字符串。
and try them both. That's obviously for RFC3339; your strings might not be in that format. Glad you didn't ask for RFC822 which is a pain to do correctly. But you should really have a method first that returns NSDate, because most uses don't actually need a string formatted for the user.
更多推荐
在iOS中解析RFC3339日期字符串的最简单的方法是什么?
发布评论