2013-02-07 49 views
0

我有以下的方法,我想用回修改日期:格式化的NSDate不工作

- (NSDate *)getCreationDate:(NSFileManager *)fileManager atPath:(NSString *)path { 
    NSError *error; 
    NSDate *date; 
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error]; 

    // Get creation date. 
    if (!error) { 
     if (fileAttributes != nil) { 
      NSDate *creationDate = [fileAttributes fileCreationDate]; 
      NSString *dateString = [creationDate description]; 
      NSLog(@"Unformatted Date Created: %@", dateString); 

      // Format date. 
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
      [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"]; 
      date = [[NSDate alloc] init]; 
      date = [dateFormatter dateFromString:dateString]; 
      NSLog(@"Formatted Date Created: %@", [date description]); 
     } else { 
      NSLog(@"File attributes not found."); 
     } 
    } else { 
     NSLog(@"%@", [error localizedDescription]); 
    } 

    return date; 
} 

的問題是格式化的日期是回來爲空。

輸出:

創建無格式的日期:2013年2月6日4時44分57秒+0000

格式化創建日期:(空)

+1

您需要查看文檔。 'description'沒有定義的返回格式;你試圖依靠無證行爲。我建議你再讀一遍'NSDate'是什麼;你似乎已經發明瞭一種觀念,即它沒有時就有格式。這只是一個特定時刻的不透明表示。 – Tommy

+2

你的代碼有太多錯誤,很難知道從哪裏開始。 –

回答

3

有沒有這樣的事情格式化的NSDate。這只是一個沒有格式的日期。描述方法用於調試和記錄,並使用任何想要的格式。

NSDateFormatter用於以指定的格式創建NSDate的NSString表示。你的方法可以用這個替換,做同樣的事情。

- (NSDate *)getCreationDate:(NSFileManager *)fileManager atPath:(NSString *)path { 
    NSError *error; 
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error]; 

    // Get creation date. 
    if (!error) { 
     if (fileAttributes != nil) { 
      return [fileAttributes fileCreationDate]; 
     } else { 
      NSLog(@"File attributes not found."); 
     } 
    } else { 
     NSLog(@"%@", [error localizedDescription]); 
    } 

    return nil; 
} 

如果要顯示日期,請格式化。使用NSDateFormatter將其轉換爲格式化的NSString。

此外,該行

date = [[NSDate alloc] init]; 
    date = [dateFormatter dateFromString:dateString]; 

創建一個新的日期,然後把它扔掉。第一行是不必要的。

+2

誰能負責解釋對這個答案的投票?這是正確的:'NSDate's沒有格式。 'fileCreationDate'是你直接從屬性中獲得的東西。即使他對日期格式化程序的使用完全錯誤,也不清楚爲什麼原始作者想要創建一個日期,然後將其丟棄並用格式化程序替換它。 – Tommy

+0

+1絕對正確。 –

+0

積分。謝謝。 – fuzz

0

你不納入時間區域轉換爲時間格式,並且時間格式錯誤。它應該是

yyyy-MM-dd HH:mm:ss ZZZZ 
+1

而downvote的原因是:*** ??? *** – 2013-02-07 00:54:06

+0

它仍然返回null與您的答案以及。我沒有downvote或btw。 – fuzz

+1

@gotnull從那以後我做了一個編輯 - 檢查日期的格式(不僅僅是時間)。還要確保該字符串不包含任何無關的空格。 – 2013-02-07 00:59:55