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:
When you save your data, bind your date value in the sql statement like this way:
NSDateFormatter*dateFormat = [[NSDateFormatteralloc] init];[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSString*dateString=[dateFormat stringFromDate:[NSDatedate]];sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);
and when you retrieve data you have to write this code:NSDateFormatter*dateFormat = [[NSDateFormatteralloc] init];[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSDate*myDate =[dateFormat dateFromString:[NSStringstringWithUTF8String:(char*)sqlite3_column_text(selectstmt, 1)]];
now you have a variable myDate of NSDate type which you can render in your way:
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];[formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);
You must have to remember 3 things:- in your SQLite date field type should be DATETIME
- Date format should be same when you store and when you retrieve
- 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