【问题标题】:NSDateFormatter and Strings with Timezone Format "+HH:mm"NSDateFormatter 和时区格式“+HH:mm”的字符串
【发布时间】:2023-04-09 06:16:02
【问题描述】:

更新

从 iOS 7 开始,NSDateFormatter 确实在以这种格式呈现字符串时确实会创建一个 NSDate:

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ""];

NSLog(@"non–nil date, even honoring the 7–minute–offset in the time–zone on iOS 7: %@",
     [formatter dateFromString:@"2011-07-12T18:07:31+02:07"]);

对于 iOS 6,答案是不使用 NSDateFormatter……


好的,至此我已经阅读完毕

关于如何使用NSDateFormatter 从字符串中创建NSDate

我也偶然发现了 Peter Hosey 的 ISO8601DateFormatter
看着他的实现,我想知道:

难道没有一种既正确理智的方法可以将这样的字符串2011-07-12T18:07:31+02:00 转换为NSDate

  • 如果最后一个冒号不存在也没关系。
  • 如果在“+”号前加上GMT 是没有问题的,但是...
  • 事实并非如此。

我可以破解它为我的应用程序工作(使用格式@"yyyy'-'MM'-'dd'T'HH':'mm':'ssz':'00")但那是 - 当然 - 不正确因为它会丢弃分钟信息时区。

我也可以用空字符串替换最后一个冒号,但我也认为这是一种黑客攻击。

那么,有什么秘诀可以让NSDateFormatter 从上面获取那个字符串并给我一个有效且正确的NSDate


旁白:

我在某个地方找到了提示,可以使用+[NSDate dateWithNaturalLanguageString:] 来实现我的目标。这——然而——只设置日期,而不是时间! (嗯,它确实设置了时间,但只考虑了时区偏移,而不是 HH:mm:ss 部分......)

【问题讨论】:

  • 您是否找到了适用于 ISO8601 偏移的实际解决方案(不是 hack)?
  • @delirus 不幸的是,不是 :-(
  • 感谢您的回复 :) 我发现 Peter Hosey 的 ISO8601DateFormatter 值得考虑,但据报道它非常慢(请参阅 stackoverflow.com/questions/2201216/…

标签: nsdateformatter iso8601 timezone-offset


【解决方案1】:

这个问题有点老了,但我遇到了同样的问题。我想出了一些代码,这是一个答案,可能对其他人有用......

我使用正则表达式来解析 ISO-8601 字符串并将输出抓取到一堆字符串中,然后您可以使用它来创建自己的字符串以传递给 NSDateFormatter(即删除冒号等),或者如果您总是想要相同的输出字符串,只需从调用 NSRegularExpression 的结果中创建。

//    ISO-8601 regex: 
//        YYYY-MM-DDThh:mm[:ss[.nnnnnnn]][{+|-}hh:mm]
// Unfortunately NSDateFormatter does not parse iso-8601 out of the box,
// so we need to use a regex and build up a date string ourselves.
static const char * REGEX_ISO8601_TIMESTAMP = 
            "\\A(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})" // Mandatory - YYYY-MM-DDThh:mm
            "(?:"
            ":(\\d{2})"                                       // Optional - :ss
            "(?:"
            "[.](\\d{1,6})"                                   // Optional - .nnnnnn
            ")?"
            ")?"
            "(?:"
            "([+-])(\\d{2}):(\\d{2})|Z"                       // Optional -[+-]hh:mm or Z
            ")?\\z";

// Extract all the parts of the timestamp
NSError *error = NULL;
NSString *regexString = [[NSString alloc] initWithUTF8String:REGEX_ISO8601_TIMESTAMP];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSArray *matches = [regex matchesInString:timestamp
                              options:0
                                range:NSMakeRange(0, [timestamp length])];

// Groups:
//
// elements start at 1 in the array returned from regex, as [0] contains the original string.
//
// MANDATORY - must exist as per ISO standard
//  1  - YYYY
//  2  - MM
//  3  - DD
//  4  - hh
//  5  - mm
// OPTIONAL (each one can be optional)
//  6  - ss
//  7  - nn (microseconds)
//  8  - offset sign (+/-)
//  9  - offset hour
//  10 - offset min
// put the parts into a string which will then be recognised by NSDateFormatter
// (which is acutally RFC822 format)

// mandatory init'd to nil, optional set to defaults.
NSString *YYYY, *MM, *DD, *hh, *mm, *ss, *nn, *sign, *Zhh, *Zmm;
NSRange tempRange;

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSInteger matchCount = [match numberOfRanges] - 1;
    NSUInteger idx = 1;

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        YYYY = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        MM   = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
         tempRange = [match rangeAtIndex:idx++];
         DD   = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        hh   = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        mm   = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        ss   = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        nn = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        sign = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        Zhh  = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }

    if (idx < matchCount) {
        tempRange = [match rangeAtIndex:idx++];
        Zmm  = tempRange.location != NSNotFound ? [timestamp substringWithRange:tempRange] : nil;
    }
}

希望这对某人有所帮助!

【讨论】:

  • 我完全没想到会有任何答案了。看到正则表达式让我想起了为什么我以前没有遵循那条路线;-) 但是当然,你的答案是正确的,所以+1 BTW:你可以使用NSString * const VARIABLE_NAME = …; 直接定义 NSString 常量
【解决方案2】:

老问题,但我在某人的要点上找到了正确答案:

https://gist.github.com/soffes/840291

它解析和创建 ISO-8601 字符串,比 NSDateFormatter 更快

代码如下:

+ (NSDate *)dateFromISO8601String:(NSString *)string {
    if (!string) {
        return nil;
    }

    struct tm tm;
    time_t t;    

    strptime([string cStringUsingEncoding:NSUTF8StringEncoding], "%Y-%m-%dT%H:%M:%S%z", &tm);
    tm.tm_isdst = -1;
    t = mktime(&tm);

    return [NSDate dateWithTimeIntervalSince1970:t + [[NSTimeZone localTimeZone] secondsFromGMT]];
}


- (NSString *)ISO8601String {
    struct tm *timeinfo;
    char buffer[80];

    time_t rawtime = [self timeIntervalSince1970] - [[NSTimeZone localTimeZone] secondsFromGMT];
    timeinfo = localtime(&rawtime);

    strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S%z", timeinfo);

    return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

【讨论】:

  • 现在这是一个仅链接的答案。这是有问题的,因为链接可能会死掉。请将重要细节复制(并注明出处)到您的帖子中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 2015-06-28
相关资源
最近更新 更多