TimeStamp Java和SQLite之间的区别

时间:2015-07-11 09:45:37

标签: java android sqlite time unix-timestamp

您好,我有SLQLite数据库,其中我有表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',#39; now')的值,则以下SQL查询可以正常工作

SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:5)

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

使用时

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

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

使用时

strftime('%s','now')

输出值为,如here所述。

因此,这可能是导致两个值不匹配的原因。 当然,以秒为单位的值可能会经历一些舍入,这可能会稍微改变其值。

答案 1 :(得分:-1)

我将尝试为您提供在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
    }
相关问题