TimeStamp Difference Between Java and SQLite

前端 未结 2 926
北海茫月
北海茫月 2021-01-21 15:38

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 IN         


        
相关标签:
2条回答
  • 2021-01-21 16:16

    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.

    0 讨论(0)
  • 2021-01-21 16:27

    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
        }
    
    0 讨论(0)
提交回复
热议问题