NSDate and Sqlite3 in iPhone

While working with NSDate and sqlite3 on iPhone the common problem many people face is about storing and retrieving NSDate from sqlite3 database. There are mainly two methods to do so, one is to get the time interval (timeIntervalSince1970) from reference date and save the interval as double value in the database, second is to convert date into string using NSDateFormatter and save the text value in the database.

NOTE: The type of column where we want to store NSDate should be DATETIME in both the methods.

Method 1: using timeIntervalSince1970

Writing NSDate to sqlite3 DB

NSDate *dateToWrite = [NSDate date]; // current date
double valueToWrite = [date timeIntervalSince1970];
// save "valueToWrite" in DB as DOUBLE

Read NSDate from sqlite3 DB

//read double from sqlite3 DB n store it in valueFromDB(double)
NSDate *dateFromDB = [NSDate dateWithTimeIntervalSince1970:valueFromDB];

Method 2: using NSDateFormatter ( i prefer )

Writing NSDate to sqlite3 DB

NSDate *dateToWrite = [NSDate date]; // current date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *stringToWrite = [dateFormatter stringFromDate:dateToWrite];
//save "stringToWrite" in DB as TEXT [dateFormatter release], dateFormatter = nil;

Reading NSDate from sqlite3 DB

//read TEXT from sqlite3 DB n store it in stringFromDB(NSString*)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromDB = [dateFormatter dateFromString:stringFromDB];
[dateFormatter release], dateFormatter = nil;

I personally prefer the 2nd method here though it takes more number of lines to do it. ( sometimes it’s better to write more number of lines )

While accessing database file from terminal we can easily read the stored date as it is very much humanly readable.

Happy Coding…