Java 和 SQLite 之间的时间戳差异

TimeStamp Difference Between Java and SQLite

你好,我有 SLQLite 数据库,其中有 table water_logs

CREATE TABLE water_logs( 
_id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
icon INTEGER NOT NULL,
date INTEGER NOT NULL);

我以毫秒为单位存储日期。

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

我的问题是我想使用 strftime 函数从我的日期列中获取日期。问题是 tjat java 日历时间戳不同于 SLQLite 时间戳

1436859563832 --> result from cal.getTimeInMillis();

1436607407--> SELECT strftime('%s','now')

我实际上想做的是按天对记录进行分组。如果将 SELECT strftime('%s','now') 的值粘贴到日期列

中,则以下 SQL 查询工作得很好
SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')

我会尽力为您提供在 SQLite 数据库中存储日期的最佳方式。

1) 始终使用整数来存储日期。

2) 使用此实用程序方法将日期存储到数据库中,

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

喜欢,

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

3) 使用此实用方法加载日期,

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

喜欢,

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

4) 您还可以使用简单的 ORDER 子句按日期对数据进行排序,

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
    }

在我看来,您使用了 2 种不同的值类型。

当您使用

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

输出值以 毫秒为单位 ,如 here 所述。

当你使用

strftime('%s','now')

输出值以 秒为单位 ,如 here 所述。

所以,这可能是两个值不匹配的原因。 当然,以秒为单位的值可能会进行一些舍入,这可能会稍微改变它的值。