Android SQLite可能的错误:插入日期

时间:2015-07-30 16:07:15

标签: android sqlite

以下是数据库处理程序类中用于管理SQLitedatabase表的一些代码。日期插入为04082015,但输出为40082015,如果日期大于10,则日期不会发生此错误。

我正在创建表格如下

@Override
public void onCreate(SQLiteDatabase db) {
        String create_college_table = "CREATE TABLE " + TableName + " (" +
                "  `"+KEY_ID+"` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                "  `"+KEY_DATE+"` DATETIME NOT NULL UNIQUE,\n" +
                "  `"+KEY_JSON+"` longtext NOT NULL\n" +
                ")";
        db.execSQL(create_college_table);
}

现在,在上表中插入一行:

public void testit() {
    // write the row into the database:
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues insertValues = new ContentValues();
    // DATE IS FOURTH OF AUGUST 2015
    insertValues.put(KEY_DATE, "04082015");
    insertValues.put(KEY_JSON, "{test}");
    db.insert(
            TableName,
            null,
            insertValues
    );


    // Now read from the database, select the row that was
    // just inserted
    String selectQuery = "SELECT * FROM " + TableName + " " +
            "WHERE " + KEY_JSON + " = '{test}'";
    SQLiteDatabase db_read = this.getWritableDatabase();
    Cursor cursor = db_read.rawQuery(selectQuery, null);
    // Viewing the log the inserted date (04082015) has been
    // outputted as 40082015, this does not occur with dates
    // were the day in the month is ten or larger?!
    Log.e("testMethod", DatabaseUtils.dumpCursorToString(cursor));
}

1 个答案:

答案 0 :(得分:4)

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 

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