Search code examples
sqliteios4timestamp

How would I store NSDate in a SQLite database?


In my SQLite database I have a column named datekey of type TIMESTAMP.

How would i store my NSDate object in the database?

From one of my classes I have already converted an NSString to appropriate date like this

dateStr = [NSString stringWithFormat:@"%@ 00:00:00 AM +0000",dateStr];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss a Z"];
NSDate *dateToBeReturned = [formatter dateFromString:dateStr];

Now I want to store this "dateToBeReturned" in to the SQLite database.

Please help


Solution

  • A timestamp is an integer of seconds since 1970, thus we can use the following method:

    [[NSDate date] timeIntervalSince1970];
    

    Replace [NSDate date] with your NSDate object.

    Update:

    To clarify, TimeInterval returned by NSDate is of type Double so you might want to be careful with the casting as numbers can sometimes behave oddly.

    Another thing that I forgot to mention was that this timestamp does not contain timezone information that could maybe be relevant for your particular application. There are string formats available that do store this using NSDateFormatter, but you could also just add a separate column containing the timezone information.