简体   繁体   中英

TimeStamp Difference Between Java and SQLite

Hello I have and SLQLite database in which I have table water_logs

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

I store date in milliseconds.

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

My problem is I want to get the day from the my date column using strftime function. The problem is tjat java calendar timestamp is different from SLQLite time stamp

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

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

What I'm actually trying to do is to group records by day. The following SQL query works just fine if value of SELECT strftime('%s','now') is paste in the date column

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

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM