Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to save correct Date using CoreData
    primarykey
    data
    text
    <p>I created a CoreData application using the Cocoa Touch Template. I modified the included .xcdatamodel file to have an attribute called 'Date' with datatype of 'Date' and other string attributes.</p> <p>I use following codes to save data for the 'Date' field:</p> <pre><code>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:&amp;error]) { // Handle the error... } </code></pre> <p>To show the data in TableView I write following code in cellForRowAtIndexPath: method:</p> <pre><code>// 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]]; </code></pre> <p>I am really surprised that cell in TableView shows - 01 Jan 1970: Test</p> <p>I also tried to use NSDateComponents instead of NSDateFormatter so I changed the code for saving date with:</p> <pre><code> 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]; </code></pre> <p>This time surprisingly cell displayed - 60 Mar 2010.</p> <p>So I get 2 different but wrong values, but am unable to show the correct value which should be - 01 Mar 2010. I am really at loss of ideas on what could be going wrong here. </p> <p>Can anybody suggest me where can I begin looking? Is there anything wrong with my code? Are there some well recognised issues with saving dates using CoreData?</p> <p>Looking forward to your replies. Thanks in advance. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload