TimeStamp Difference Between Java and SQLite

淺唱寂寞╮ 提交于 2019-12-01 23:43:39

Seems to me that you are using 2 different value types.

When you use

Calendar cal = Calendar.getInstance(); 
long time = cal.getTimeInMillis();

The output value is in Milliseconds, as described here.

While when you use

strftime('%s','now')

The output value is in Seconds, as described here.

So, that might be the cause for the mismatch between the two values. Of course that the value in seconds might undergo some rounding which might change its value a little.

I will try to provide you the best way to store Dates in SQLite database.

1) Always use integers to store the dates.

2) Use this utility method to store the dates into the database,

public static Long saveDate(Date date) {
    if (date != null) {
        return date.getTime();
    }
    return null;
}

Like,

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, saveDate(entity.getDate()));
long id = db.insertOrThrow(TABLE_NAME, null, values);

3) Use this utility method to load date,

public static Date loadDate(Cursor cursor, int index) {
    if (cursor.isNull(index)) {
        return null;
    }
    return new Date(cursor.getLong(index));
}

like,

entity.setDate(loadDate(cursor, INDEX));

4) You can also order the data by date using simple ORDER clause,

public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";

//...

    Cursor cursor = rawQuery(QUERY, null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        // Process results
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!