How to insert a SQLite record with a datetime set to 'now' in Android application?

droidguy picture droidguy · Apr 16, 2009 · Viewed 223.5k times · Source

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

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

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

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

Answer

e-satis picture e-satis · May 4, 2009

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

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

    mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
    
  • 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);