Wednesday 5 February 2014

Objective-C and sqlite’s DATETIME type

Well, I am sharing here just the core things regarding date formatting for saving and retrieving the data from Sqlite to Objective C or vice versa. If you have any problem with this code snippet then I will share the full code that I used for my app.


When you save your data, bind your date value in the sql statement like this way:
  1. NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  2. [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSString *dateString=[dateFormat stringFromDate:[NSDate date]];
  4. sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);

and when you retrieve data you have to write this code:

  1. NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  2. [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];

now you have a variable myDate of NSDate type which you can render in your way:

  1. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  2. [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);

You must have to remember 3 things:
  1. in your SQLite date field type should be DATETIME
  2. Date format should be same when you store and when you retrieve
  3. Now you can show in your won way but following the format. Bellow the format details has given.

 
Format: 

     'dd' = Day 01-31
     'MM' = Month 01-12
     'yyyy' = Year 2000
     'HH' = Hour in 24 hour
     'hh' = Hour in 12 hour
     'mm' = Minute 00-59
     'ss' = Second 00-59
     'a' = AM / PM


No comments:

Post a Comment