HELLO i am trying to insert Current date in my database table i have a column dateVisited of type datetime
NSDateFormatter *forma开发者_开发知识库tter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"]; //this is the sqlite's format
NSDate *stringTime = [NSDate date];
NSString *formattedDateStringTime = [formatter stringFromDate:stringTime];
sqlStr = [NSString stringWithFormat:@"Insert into AnwaltHistory (id,dateVisited) values (%d,'%@')",Id formattedDateStringTime];
NSLog(@"%@",sqlStr);
BOOL Res = [appDelegate InsUpdateDelData: sqlStr];
if (Res)
{
NSLog(@"The Following instrunction is excuted successfully !");
}
else
{
NSLog(@"The Following instrunction Failed to execute !");
}
the statement executes successfully but when i actually go and check the table it says invalid date... i dont know why as i have printed sqlstr i copy paste from the console and paste it in sqlite and run it manually it runs perfectly fine and has the actual date.... can any one guide me where i am mistaken :S....... please
Why not use:
"Insert into AnwaltHistory (id,dateVisited) values (%d,datetime())",Id
You could try this:
double dateVisited = [[NSDate date] timeIntervalSince1970]; //now
// save dateVisited to your 'dateVisited' field
According to the official documents, the DateTime on SQLITE should be in ISO8601 format (AKA: a string of ("YYYY-MM-DD HH:MM:SS.SSS"))
Therefore, to store the date, you should format your date string, below is a code to help you with this:
NSDate *SourceDate = [NSDate date]; // Or whatever NSDATE you like...
NSDateFormatter *MyDateFormatter = [[NSDateFormatter alloc] init];
[MyDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSString *SQLiteQuery = [NSString stringWithFormat:@"Insert into YourTable(YourDateField) values ('%@')", [MyDateFormatter stringFromDate:SourceDate]];
This should do it, give's a shout if you need more help,
Cheers H
精彩评论