1

When I store a date in CoreData as [NSDate date], it is saved -5:30 difference. In core data I used attribute type as date.

How to store NSdate with timeZone?

Update: Here is the code I am using:

To store the date:

database = (DataBase*) [fetchResults objectAtIndex:indexVal]; 
[database setDate:[NSDate date]]; 
NSError error = nil; 
[managedObjectContext save:&error] 

To retrieve the date:

DataBase *newDataBase = (DataBase) [fetchResults objectAtIndex:i]; 
NSDate *RetrivedDate = [newDataBase Date]; 
NSLog(@"Retrived Date :",RetrivedDate"); 

Before storing I log it. It shows current date and time. After storing I immediately fetched the date . but it showed 1 day delayed date..

jrturton
  • 118,105
  • 32
  • 252
  • 268
Siva
  • 95
  • 6

1 Answers1

1

NSDate doesn't have a time zone. It stores dates as a number of seconds since a reference date in GMT.

The time zone is applied when you format the date for display using NSDateFormatter. This will pick up the device time zone by default.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • But I stored date as [NSDate date] and retrived date as NSDate *dat = [db Date]; It shows one day and one hour difference.. How to resolve it. – Siva Oct 14 '11 at 06:22
  • And Also I checked the difference between the two dates immediately after stored in Db. then got a difference of one day. Please help – Siva Oct 14 '11 at 06:27
  • Can you update you question with code if you have a specific example? – jrturton Oct 14 '11 at 06:27
  • Here Is My code //storing database = (DataBase*) [fetchResults objectAtIndex:indexVal]; [database setDate:[NSDate date]]; NSError *error = nil; [managedObjectContext save:&error] //retriving DataBase *newDataBase = (DataBase*) [fetchResults objectAtIndex:i]; NSDate *RetrivedDate = [newDataBase Date]; NSLog(@"Retrived Date :",RetrivedDate"); Here Retrived date gives 1 day and 1 hour and 15 min difference. – Siva Oct 14 '11 at 06:49
  • I did. while Storing before I log it. it shows current date and time . After stored I immediately fetched the date . but it showed 1 day delayed date.. AnyWay Thanks for your comments – Siva Oct 14 '11 at 08:20
  • I have just attempted this myself with a basic project. NSLogging the date before adding to and after retrieving a managed object gives exactly the same information in the log, which is the current time in GMT. – jrturton Oct 14 '11 at 13:01
  • @jrturton there is a similar question http://stackoverflow.com/questions/31697771/save-date-in-gmt-timezone-using-core-data .Can you help me? – SandeepAggarwal Jul 29 '15 at 11:56
  • @SandeepAggarwal my answer is exactly the same. NSDate has no idea about time zones, it represents a specific moment in time. Yours is a problem with formatting output, not data storage. – jrturton Jul 29 '15 at 17:20
  • @jrturton but when I saw it in database the date was in my phone's timezone, can't I see it in UTC? – SandeepAggarwal Jul 29 '15 at 17:26