将Adobe PDF日期字符串转换为NSDate

时间:2010-11-29 11:45:49

标签: iphone objective-c ipad ios nsdate

输入字符串为'20100908041312'

格式为年,月,日,小时,分钟,秒,时区

我试图将其转换为NSDate,其中包含:@"yyyyMMddHHmmsszz"

但NSDate是零,有人看到我做错了吗?

-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{

    //20100908041312
    //year month day Hours minutes seconds and time zone

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMddHHmmsszz"]; 
    NSDate *date = [dateFormat dateFromString:_string];
    //date is nil...
    [dateFormat release];

    return date;
}

编辑:它的时区打破

EDIT2:@"yyyyMMddHHmmssTZD"停止返回nil,但dosnt正确选择时区

EDIT3:这是我最后使用的代码......我发现格式从PDF变为PDF所以代码处理我发现的变化,在某些情况下这不会正确提取时区。

-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

    NSString * formatCheck = [_string substringToIndex:2];

    if(![formatCheck isEqualToString:@"D:"])
    {
        NSLog(@"ERROR: Date String wasnt in expected format");
        return nil;//return [NSDate date];
    }

    NSString * extract = [_string substringFromIndex:2];    

    //NSLog(@"DATESTRING:'%@'",extract);NSLog(@"DATELENGTH:%i",[extract length]);

    if([extract length]>14)
    {
        [dateFormat setDateFormat:@"yyyyMMddHHmmssTZD"];
    }
    else 
    {
        [dateFormat setDateFormat:@"yyyyMMddHHmmss"];
    }   
    NSDate * date = [dateFormat dateFromString:extract]; 
    [dateFormat release];

    return date ;
}

3 个答案:

答案 0 :(得分:2)

它应遵循setDateFormat的unicode标准:http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

您应该能够以这种方式设置时区:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMddHHmmss"];
//Optionally for time zone conversations
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

亚历

答案 1 :(得分:1)

“12”不是任何Unicode日期格式模式的有效时区,因此NSDateFormatter不返回任何内容。 http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

您可能必须使用除最后两位数之外的所有数字,然后通过将Adobe的两位数字转换为适当的时区来设置新NSDate对象的时区。

答案 2 :(得分:1)

我认为这个帖子已经超过一年了,但是没有时间来回答更好的答案。

由于您指定输入字符串是Adobe PDF日期字符串,因此格式应符合PDF规范,根据规范: YYYYMMDDHHmmSSOHH'mm (省略前缀D :)。

请注意,您的输入字符串长度为14个字符,NSDate格式长度为16个字符,因此时区不在您输入的字符串中。

尽管如此,您问题的真正答案是使用 Quartz 2D CGPDFString 功能:

CFDateRef CGPDFStringCopyDate (CGPDFStringRef string );

该函数返回一个CFDateRef,它具有到NSDate的免费桥接器,因此您可以将从PDF读取的日期传递给此函数,并通过强制转换轻松返回NSDate。