iOS and SQLite date formatting

First, create table within database:

create table my_date ( date_column DATE);

Insert the date into database (format: YYYY-MM-DD HH:MM:SS)

insert into my_date(date_column) values('2011-01-01 00:00:00');

Retrieve data within iOS and parse date:


sqlite3 *database = nil;
// ...
// connect to SQLite - I assume that database 
// ...

static const char *sql = "select date_column from my_date";
sqlite3_prepare_v2(database, sql, -1, &statement, NULL);

while(sqlite3_step(statement) == SQLITE_ROW) {
  // get data as text
  const unsigned char *cstring_date = sqlite3_column_text(statement, 0);
  // convert char * to NSString
  NSString *ns_date = 
    [[NSString alloc] initWithUTF8String: (const char *) cstring_date];
  // create data formatter with proper date format
  NSDateFormatter *dateFormatter = 
    [[NSDateFormatter alloc] init];
  // note different notation of date
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  // create NSDate object from NSString
  NSDate *date = [dateFormatter dateFromString: ns_date];

  // retrieve day, month, year from NSDate object
  NSDateComponents *components = 
    [[NSCalendar currentCalendar] components:
      NSDayCalendarUnit | 
      NSMonthCalendarUnit |   
      NSYearCalendarUnit fromDate:[NSDate date]];
  NSInteger day = [components day];
  NSInteger month = [components month];
  NSInteger year = [components year];
}