【问题标题】:Unable to convert original date using dateFromString无法使用 dateFromString 转换原始日期
【发布时间】:2012-12-21 22:06:56
【问题描述】:

我正在尝试使用以下代码转换时间字符串

NSString *origDate = @"2012-12-06T09:27:18+08:00";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"yyyy-mm-dd HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate]; 

但是,当我打印 convertDate 时,它​​返回 null。我的猜测是你使用的日期格式不匹配。如何修改代码以使其正常工作?我可以使用什么格式来匹配我的字符串?

编辑(参考苹果文档后)

我查看了苹果页面上的日期格式文档,发现如下代码

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];

上面的格式似乎与我在原始日期字符串“2012-12-06T09:27:18+08:00”中的格式相匹配。但是我仍然得到一个空值。我越来越近了吗?我还能如何更新这个?

【问题讨论】:

  • 你的猜测是正确的。源日期字符串看起来很糟糕;你对此有任何控制权吗?似乎日期和时间以及时区之间应该有一个空格。但除此之外,是的,您必须更改为日期格式化程序指定的字符串。
  • @trudyscousin 它是由我的系统创建的,但我确信我可以操纵原始字符串。但是你是说没有'setDateFormat'可以用来转换我当前的字符串?
  • 不,一点也不。 Apple 文档中的This page 将引导您找到正确设置字符串所需的文档。查看“固定格式”部分。
  • @trudyscousin 我按照你的建议检查了文档,发现了一些似乎检查类似格式的东西,但它仍然返回一个空值。你介意帮我再看看我原来的帖子吗?
  • 在 iOS 5 中,您无法在时区偏移中读取带有“:”的时间戳——您必须以某种方式删除该字符。在 iOS 6 中可以,但只能使用“ZZZZZ”。

标签: objective-c date nsstring converter nsdateformatter


【解决方案1】:

根据您的原始输入,提供给日期格式化程序的此格式字符串应该可以完成工作:

@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ"

注意:我在 Mac OS X 10.8.2 下测试过。

【讨论】:

    【解决方案2】:

    格式字符串将在 iOS6(不是 iOS5 -> nil)上解析,但它对输出没有用,因为解析的日期会丢失它的时区信息。 iOS6 中的输出将类似于“2012-12-06T17:27:18Z”,这可能取决于时区是否设置为 GMT。

    我的代码:

        static NSDateFormatter    *gXmlDateFormatter = nil;
    // lazy init
    + (NSDateFormatter *)xmlDateFormatter
    {
        // e.g. updateDateTime="2012-09-18T11:06:19+00:00"
        if (gXmlDateFormatter == nil) {
            // prepare for parsinf Arinc-ISO-XML-dates input
            gXmlDateFormatter = [[NSDateFormatter alloc] init];
            gXmlDateFormatter = [NSTimeZone timeZoneForSecondsFromGMT:0];
            gXmlDateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    
            gXmlDateFormatter.dateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ";    // only parsing! in iOS 6 (iOS5 will parse nil)
    //        gXmlDateFormatter.dateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";        // all iOS but with NO colons in timeZone (add/remove)
        }
        NSLog(@"gXmlDateFormatter:%@",gXmlDateFormatter);
        return gXmlDateFormatter;
    }
    // there's a problem with the above dateformater and iOS5 creating nil-results
    + (NSDate *)dateFromXMLString:(NSString *)arincDateString
    {
        NSString *dateString = arincDateString;
    
        // xmlDateStrings may contain a ':' in the timezone part. iOS and Unicode DO NOT
        // so always remove the xml-standard colon ':' from the timezone to make it iOS/Unicode compatible
        // xml: http://www.w3schools.com/schema/schema_dtypes_date.asp
        // iOS: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns)
        NSRange zRange = NSMakeRange(arincDateString.length-3, 1);
        dateString = [arincDateString stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:zRange];
    
        NSDate *date = [self.arincDateFormatter dateFromString:dateString];
    
        if(!date)NSLog(@"PARSING arincDateString:'%@' -> (NSDate*)%@ ",arincDateString,date);
    
        return date;
    }
    + (NSString *)xmlStringFromDate:(NSDate *)date
    {
        if( !date ) return nil;        // exit on nil date
    
        @autoreleasepool {
            NSString *dateString = [self.arincDateFormatter stringFromDate:date];
    
            // iOS5 does not use a ':' in the timeZone part but xml needs it
            // so allways add the xml-standard colon ':' into the timezone
            NSMutableString *string = [NSMutableString stringWithString:dateString];
            if( 22 < string.length ) {        // prevent crashing
                [string insertString:@":" atIndex:22];
            } else {
                NSLog(@"date output string too short:%d<22",string.length);
            }
            dateString = string;
    
            if(!dateString)
                NSLog(@"OUTPUT '%@' -> (NSString*)%@",date,dateString);
            return dateString;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2014-12-24
      • 2016-01-06
      相关资源
      最近更新 更多