2010-11-29 40 views
1

輸入字符串爲「20100908041312」轉換的Adobe PDF日期字符串的NSDate

格式是年,月,日,時,分,秒,時區

,我已經奔試圖將其轉換以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:這是我最終使用的代碼。 ..i發現格式從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 ; 
} 
+2

D'oh!我沒有做任何研究! :) – 2010-11-29 12:03:37

+0

無論如何,這是非常感謝:) – 2010-11-29 12:09:11

回答

1

我承認帖子是超過一年老,但沒有時間爲更好的答案爲時已晚。

既然你指定的輸入字符串是Adobe PDF日期字符串,那麼格式應符合PDF規範,每個產品的規格有:YYYYMMDDHHmmSSOHH'mm(省略前綴d :)。

請注意,您的輸入字符串長度爲14個字符,而您的NSDate格式長度爲16個字符,因此所述時區不在您輸入的字符串中。

然而,真正的回答你的問題是使用石英2D CGPDFString功能:
 
CFDateRef CGPDFStringCopyDate (CGPDFStringRef string );

該函數返回一個CFDateRef其中有一個免費電話橋NSDate的,所以你可以將從PDF中讀取的日期傳遞給此函數,並通過投射輕鬆取回NSDate。

1

「12」不是任何Unicode日期格式模式的有效時區,所以NSDateFormatter不返回任何內容。 http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

您可能必須使用除最後兩位數以外的所有數字,然後通過將Adobe的兩位數號碼轉換爲適當的時區來設置新NSDate對象的時區。

+0

乾杯,現在的工作 – 2010-11-29 12:03:33

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:@"..."]]; 

亞歷