【问题标题】:What's the simplest way to parse RFC3339 date string in iOS?在 iOS 中解析 RFC3339 日期字符串的最简单方法是什么?
【发布时间】:2012-01-16 07:39:16
【问题描述】:

Youtube API 以 RFC3339 格式返回日期字符串。手动找到了怎么解析,反正就是太长了。

- (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;
}

我可以让一个函数包含这个,但我想知道 Cocoa 基础或标准 C 或 POSIX 库上是否有预定义的方法来做到这一点。如果有的话,我想使用它。你能告诉我有没有更简单的方法?或者,如果您确认这是最简单的方法,将不胜感激:)

【问题讨论】:

    标签: objective-c cocoa date-formatting rfc3339


    【解决方案1】:

    纯可可自带的东西正是您正在做的事情。您可以通过在其他地方(可能在init)创建日期格式化程序并在此方法中使用/重用它们来使此方法更短、更快。

    【讨论】:

    • 不幸的是,当我测试一次时,这段代码无法处理派系部分的秒数......
    • @Eonil:您需要修改格式字符串。相关规范中有为小数秒定义的格式字符:unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns
    • 哦,这看起来不错。我会试试这个:)
    【解决方案2】:

    您需要两种格式,因为小数秒是可选的,并且时区应该是 Z5,而不是 Z。因此您创建了两个具有格式的格式化程序

    @"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5"
    @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5"
    

    两个都试试。这显然是针对 RFC3339 的;您的字符串可能不是那种格式。很高兴你没有要求 RFC822 正确地做这件事很痛苦。但是你首先应该有一个返回 NSDate 的方法,因为大多数使用实际上并不需要为用户格式化的字符串。

    【讨论】:

      【解决方案3】:

      我在 Obj-c 中解析 RFC 3339 时遇到了一些问题,因为小数秒和区域似乎是可选的。

      我发现的最可靠的函数是这个 Gist(我不是它的作者):https://gist.github.com/mwaterfall/953664

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-08
        • 1970-01-01
        • 2011-08-22
        相关资源
        最近更新 更多