TimeStamp Difference Between Java and SQLite

前端 未结 2 929
北海茫月
北海茫月 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: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
        }
    

提交回复
热议问题