sqlite datetime数据类型与iphone NSdate? [英] sqlite datetime data type with iphone NSdate?

查看:208
本文介绍了sqlite datetime数据类型与iphone NSdate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在创建记录时,sqlite中有没有方法自动将时间戳保存在表中,然后可以在我的应用程序中抓取并保存为NSDate? p>或者我应该在我的iphone应用程序中创建当前时间的NSdate对象,然后将其插入数据库。如果是这样?当时数据类型应该是哪一列?一个DATETIME?

解决方案

我所做的是使用sqlite的current_timestamp(看起来像这样:2009-06-16 12:11 :24)。要做到这一点,只需将qslite表的行类型设置为

 数据类型:DATETIME
允许null: NO
默认值:CURRENT_TIMESTAMP

然后使用这样的SQL查询:

  @INSERT INTO'scores'('one','two','three')VALUES('%d','%d ','%d')

忽略日期,以便自动获取当前时间值



然后将其转换为NSDate,您可以使用像这样的NSDateFormatter:

  NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@yyyy-MM-dd HH:mm:ss]; //这是sqlite的格式
NSDate * date = [formatter dateFromString:score.datetime];

现在,您将该日期作为NSDate对象。只是不要忘记释放我们分配的NSDateFormatter:)


Is there a way in sqlite to automatically save a timestamp in the table whenever a record has been created that I can then grab and save as an NSDate in my application?

Or should I instead create the NSdate object with the current time in my iphone app, and then insert it into the database. If so? What column should the datatype be for the time? a DATETIME?

解决方案

What I do is use sqlite's current_timestamp (which looks something like this: 2009-06-16 12:11:24). To do this just set the row type of your qslite table to

Data type: "DATETIME"
Allow null: NO
Default value: CURRENT_TIMESTAMP

Then use an SQL query like this:

@"INSERT INTO 'scores' ('one', 'two', 'three') VALUES ('%d', '%d', '%d')"

ignoring the date, so that it will automatically get the current time value.

Then to convert this to an NSDate you can use an NSDateFormatter like this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //this is the sqlite's format
NSDate *date = [formatter dateFromString:score.datetime];

and now you have that date as an NSDate object. Just don't forget to release the NSDateFormatter we allocated :)

这篇关于sqlite datetime数据类型与iphone NSdate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆