如何在sqlite数据库中添加日期

Kos*_*uta 23 database sqlite android date

我有 sqlite database

    private static final String DB_PROCESS_CREATE = "create table "
        + DB_TABLE_PROCESS + "(" + PROCESS_ID
        + " integer primary key autoincrement, "
        + PROCESS_DATE + " date);";
Run Code Online (Sandbox Code Playgroud)

我创造它 db.execSQL(DB_PROCESS_CREATE);

如何在此数据库中添加日期值?我试过了 :

String date = new SimpleDateFormat("yyyy.MM.dd").format(Calendar
.getInstance().getTime());
ContentValues cv = new ContentValues();
cv.put(db.PROCESS_DATE,Date.valueOf(date));
db.mDB.insert(db.DB_TABLE_PROCESS, null, cv));
Run Code Online (Sandbox Code Playgroud)

但后来我得到error:

"The method put(String, String) in the type ContentValues is not applicable for the arguments (String, Date)".
Run Code Online (Sandbox Code Playgroud)

Hom*_*mam 47

现在,当您要将日期插入数据库时​​,可以使用此代码.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
Run Code Online (Sandbox Code Playgroud)

在数据库中插入字符串'date'

sqlite中的日期格式应为以下格式:

YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD 
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看:http://www.sqlite.org/lang_datefunc.html


Ily*_*nko 11

您无法直接在SQLite中存储日期.例如,您可以将其存储为整数值:

ContentValues cv = new ContentValues();
cv.put(db.PROCESS_DATE, new Date().getTime());
db.mDB.insert(db.DB_TABLE_PROCESS, null, cv));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的日期字段必须声明为整数:

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

从SQLite文档:SQLite没有为存储日期和/或时间而预留的存储类.相反,SQLite的内置日期和时间函数能够将日期和时间存储为TEXT,REAL或INTEGER值:

  1. TEXT为ISO8601字符串("YYYY-MM-DD HH:MM:SS.SSS").
  2. 真实如朱利安日数,根据公历4714年11月24日格林威治中午以来的天数.
  3. INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数.应用程序可以选择以任何这些格式存储日期和时间,并使用内置的日期和时间函数在格式之间自由转换.

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