如何插入一个日期时间在Android应用程序设置为'现在'一个SQLite记录? [英] How to insert a SQLite record with a datetime set to 'now' in Android application?

查看:87
本文介绍了如何插入一个日期时间在Android应用程序设置为'现在'一个SQLite记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我们有一个表创建为:

Say, we have a table created as:

  
create table notes (_id integer primary key autoincrement, created_date date)

要插入一条记录,我会使用

To insert a record, I'd use


ContentValues initialValues = new ContentValues(); 
initialValues.put("date_created", "");
long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);

但如何设置DATE_CREATED列到现在?要清楚,在

But how to set the date_created column to "now"? To make it clear, the


initialValues.put("date_created", "datetime('now')");

是不是正确的解决方案。它只是列设置为DATETIME('现在')文本。

Is not the right solution. It just sets the column to "datetime('now')" text.

推荐答案

您不能使用使用Java包装ContentValues​​的日期时间函数。要么你可以使用:

You cannot use the datetime function using the Java wrapper "ContentValues". Either you can use :

  • SQLiteDatabase.execSQL这样你就可以进入一个原始的SQL查询。

  • SQLiteDatabase.execSQL so you can enter a raw SQL query.

mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");

  • 或Java日期时间功能:

  • Or the java date time capabilities :

    // set the format to sql date time
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    Date date = new Date();
    ContentValues initialValues = new ContentValues(); 
    initialValues.put("date_created", dateFormat.format(date));
    long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);
    

  • 这篇关于如何插入一个日期时间在Android应用程序设置为'现在'一个SQLite记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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