0

你好我正在尝试在我的数据库表中插入当前日期我有一个日期时间类型的列 dateVisited

NSDateFormatter *formatter = [[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 !");
}

该语句成功执行但是当我实际去检查表时它说无效日期......我不知道为什么我打印了sqlstr我从控制台复制粘贴并将其粘贴到sqlite并手动运行它运行得很好并且有实际日期....任何人都可以指导我在哪里我弄错了:S.......请

4

3 回答 3

0

为什么不使用:

"Insert into AnwaltHistory (id,dateVisited) values (%d,datetime())",Id
于 2010-04-01T14:52:29.683 回答
0

你可以试试这个:

double dateVisited = [[NSDate date] timeIntervalSince1970]; //now
// save dateVisited to your 'dateVisited' field
于 2011-10-29T16:31:46.637 回答
0

根据官方文档,SQLITE 上的 DateTime 应该是 ISO8601 格式(又名:a string of ("YYYY-MM-DD HH:MM:SS.SSS"))

因此,要存储日期,您应该格式化您的日期字符串,下面是帮助您解决此问题的代码:

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]];

这应该可以,如果您需要更多帮助,请大声喊叫,

干杯H

于 2021-11-08T12:38:55.830 回答