How to insert a SQLite record with a datetime set to 'now' in Android application?
Solution 1:
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);
Solution 2:
In my code I use DATETIME DEFAULT CURRENT_TIMESTAMP
as the type and constraint of the column.
In your case your table definition would be
create table notes (
_id integer primary key autoincrement,
created_date date default CURRENT_DATE
)
Solution 3:
Method 1
CURRENT_TIME – Inserts only time
CURRENT_DATE – Inserts only date
CURRENT_TIMESTAMP – Inserts both time and date
CREATE TABLE users(
id INTEGER PRIMARY KEY,
username TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Method 2
db.execSQL("INSERT INTO users(username, created_at)
VALUES('ravitamada', 'datetime()'");
Method 3 Using java Date functions
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
ContentValues values = new ContentValues();
values.put('username', 'ravitamada');
values.put('created_at', getDateTime());
// insert the row
long id = db.insert('users', null, values);
Solution 4:
There are a couple options you can use:
- You could try using the string "(DATETIME('now'))" instead.
- Insert the datetime yourself, ie with System.currentTimeMillis()
- When creating the SQLite table, specify a default value for the created_date column as the current date time.
- Use SQLiteDatabase.execSQL to insert directly.
Solution 5:
To me, the problem looks like you're sending "datetime('now')"
as a string, rather than a value.
My thought is to find a way to grab the current date/time and send it to your database as a date/time value, or find a way to use SQLite's built-in (DATETIME('NOW'))
parameter
Check out the anwsers at this SO.com question - they might lead you in the right direction.
Hopefully this helps!