110

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.

Iamat8
  • 3,888
  • 9
  • 25
  • 35
droidguy
  • 1,101
  • 2
  • 8
  • 4
  • 1
    One problem here is that Android uses SQLite for the DB. You can set a column to a certain type but that just sets the columns 'affinity'. SQLite will let you put any value in any column regardless of how it's declared. To SQLite putting the string 'date' in anywhere is pretty okay. sqlite.org has a more thorough explanation. I'm voting up e-satis's answer below, that's how I do it (specifically the Java way). – Will May 10 '09 at 23:43

10 Answers10

199

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);
    
Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
Bite code
  • 578,959
  • 113
  • 301
  • 329
45

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
)
skaffman
  • 398,947
  • 96
  • 818
  • 769
Gautier Hayoun
  • 2,922
  • 24
  • 17
35

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);
Rikin Patel
  • 8,848
  • 7
  • 70
  • 78
  • Curious, can you show how you would switch the resulting string back to a DATE object? – erik Apr 29 '15 at 17:21
  • @erik Can you give more information, I am not exactly getting what you said. – Rikin Patel Apr 30 '15 at 03:08
  • so above you are taking a Date object and converting it to a string to be placed in a sqlite column.. but when you pull that string from the database, how do you convert it back to a Date object? – erik Apr 30 '15 at 03:34
  • 2
    @erik SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.parse(created_at); – Saksham Jun 13 '16 at 15:50
  • @erik I think we don't required to convert back string to date because in DB we have datetime column so it will save as datetime. – Rikin Patel Aug 16 '21 at 03:44
8

There are a couple options you can use:

  1. You could try using the string "(DATETIME('now'))" instead.
  2. Insert the datetime yourself, ie with System.currentTimeMillis()
  3. When creating the SQLite table, specify a default value for the created_date column as the current date time.
  4. Use SQLiteDatabase.execSQL to insert directly.
sooniln
  • 14,607
  • 4
  • 29
  • 35
  • Number 1 doesn't work (at least not when using `ContentValues` and `update()`, it just puts the string `DATETIME('now')` in the column. – Bart Friederichs Nov 13 '13 at 09:44
  • 1
    The second one has problems with timezones. I inserted a record with a `DEFAULT CURRENT_TIMESTAMP` and later used `System.currentTimeMillis()` to update. I see an hour difference. – Bart Friederichs Nov 13 '13 at 09:50
  • @sooniln Have you verified that (DATETIME('now')) will indeed insert the current datetime? – IgorGanapolsky Oct 08 '14 at 16:54
  • If you want to add local datetime , try to use "datetime('now','localtime')" instead – Simon May 15 '15 at 03:35
7

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!

Community
  • 1
  • 1
Jared Harley
  • 8,219
  • 4
  • 39
  • 48
5

You can use the function of java that is:

ContentValues cv = new ContentValues();
cv.put(Constants.DATE, java.lang.System.currentTimeMillis());  

In this way, in your db you save a number.
This number could be interpreted in this way:

    DateFormat dateF = DateFormat.getDateTimeInstance();
    String data = dateF.format(new Date(l));

Instead of l into new Date(l), you shoul insert the number into the column of date.
So, you have your date.
For example i save in my db this number : 1332342462078
But when i call the method above i have this result: 21-mar-2012 16.07.42

Marco Gallella
  • 793
  • 1
  • 11
  • 18
3

Based on @e-satis answer I created a private method on my "DBTools" class so adding current date is now really easy:

...
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
...
        private String getNow(){
            // set the format to sql date time
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            return dateFormat.format(date);
        }
...

Use it now like this: values.put("lastUpdate", getNow());

Cedric Simon
  • 4,571
  • 4
  • 40
  • 52
1

Works for me perfect:

    values.put(DBHelper.COLUMN_RECEIVEDATE, geo.getReceiveDate().getTime());

Save your date as a long.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
1

This code example may do what you want:

http://androidcookbook.com/Recipe.seam?recipeId=413

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
0

Make sure that the field is not marked as 'not null' at the same time as you are trying to insert a default time stamp using the expression "(DATETIME('now'))"