How to add date in sqlite database How to add date in sqlite database database database

How to add date in sqlite database


Now when you want to insert date to database, you can use this code.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String date = sdf.format(new Date());

In database insert the string 'date'

The date format in sqlite should be of following format:

YYYY-MM-DDYYYY-MM-DD HH:MMYYYY-MM-DD HH:MM:SSYYYY-MM-DD HH:MM:SS.SSSYYYY-MM-DDTHH:MMYYYY-MM-DDTHH:MM:SSYYYY-MM-DDTHH:MM:SS.SSSHH:MMHH:MM:SSHH:MM:SS.SSSnowDDDDDDDDDD 

For more details, have a look: http://www.sqlite.org/lang_datefunc.html


You cannot store date in SQLite directly. For example, you can store it as integer value:

ContentValues cv = new ContentValues();cv.put(db.PROCESS_DATE, new Date().getTime());db.mDB.insert(db.DB_TABLE_PROCESS, null, cv));

In this case your date field must be declared as integer:

private static final String DB_PROCESS_CREATE = "create table "        + DB_TABLE_PROCESS + "(" + PROCESS_ID        + " integer primary key autoincrement, "        + PROCESS_DATE + " integer);";

From SQLite docs: SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  1. TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  2. REAL as Julianday numbers, the number of days since noon in Greenwich on November24, 4714 B.C. according to the proleptic Gregorian calendar.
  3. INTEGERas Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.Applications can chose to store dates and times in any of theseformats and freely convert between formats using the built-in dateand time functions.

See http://www.sqlite.org/datatype3.html


The best way to put a date into a database would be using the long value of it. I tried to do what you were doing, and it had a similar error. Instead of a string, put in a numerical value. It can take the long value, which I believe is the millisecond value of some sort. It can then be reconverted when you pull it out.