2010-03-04 33 views
1

我使用Cocoa Touch模板創建了一個CoreData應用程序。我修改了包含的.xcdatamodel文件,使其具有名爲Date的屬性,其數據類型爲Date和其他字符串屬性。無法使用CoreData保存正確的日期

我用下面的代碼保存數據的「日期」字段:

NSDateFormatter *dateFormatter=[[[NSDateFormatter alloc] init] autorelease] ; 
[dateFormatter setDateFormat:@"YYYY-MM-DD"]; 
NSDate *date= [[[NSDate alloc] init] autorelease]; 
date=[dateFormatter dateFromString:@"2010-03-01"]; 

[newManagedObject setValue:date forKey:@"Date"]; 

NSError *error; 
    if (![context save:&error]) { 
     // Handle the error... 
    } 

爲了證明我寫下面的的cellForRowAtIndexPath代碼TableView中的數據:方法:

// Configure the cell. 

NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath]; 

//Formatting Date Portion of Name 
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"DD MMM YYYY"]; 

NSString *fName= [NSString stringWithFormat: @"%@: %@", [dateFormatter stringFromDate:[managedObject valueForKey:@"Date"]],[[managedObject valueForKey:@"Name"] description]]; 

我真的驚訝於TableView中的單元格顯示 - 01年1月1日:測試

我也嘗試使用NSDateComponents而不是NSDateFormatter,所以我更改了保存日期的代碼:

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setDay:1]; 
[comps setMonth:3]; 
[comps setYear:2010]; 
NSCalendar *gregorian = [[NSCalendar alloc] 
         initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *date = [gregorian dateFromComponents:comps]; 
[comps release]; 

出奇的單元格中顯示此時間 - 2010年01月我真的在 - 2010年

所以我得到2個不同的,但錯誤的價值觀,但我無法顯示正確的值應該是60月對這裏可能出錯的想法丟失了。

有人可以建議我從哪裏開始尋找?我的代碼有什麼問題嗎?使用CoreData保存日期是否存在一些公認的問題?

期待您的回覆。提前致謝。

回答

0

在NSDateFormatter版本中,格式字符串應該是@「yyyy-MM-dd」(小寫字母y和d)。

請參閱日期格式設置模式: http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

對於NSDateComponents版本,什麼是你用來顯示在單元格中的日期代碼?

+0

哦,我覺得這個錯誤很愚蠢。感謝您花時間回覆。 對於顯示我使用相同的代碼,這就是爲什麼NSDateComponents代碼正確插入日期,但我以錯誤的格式顯示它們。在NSDateFormatter的情況下,我插入錯誤的日期並顯示錯誤的日期。 感謝您在unicode.org上分享非常翔實的鏈接。再次感謝。 – 2010-03-05 09:32:59