如何在Sqlite Android中根据日期获取数据

时间:2016-09-08 17:48:10

标签: android sqlite android-sqlite

在我的数据库表中,我有一个Date列和另外两列 我想编写一个查询,根据系统日期检索已保存的数据today。我尝试了很多查询,但它无法正常工作.. 请帮助任何帮助感谢

提前致谢:)

public class UserDbHelper extends SQLiteOpenHelper {
    
        public static final String DATABASENAME = "DATABASENAME2";
        public static final int DB_VERSION = 1;
        
        public UserDbHelper(Context context)
        {
            super(context,DATABASENAME,null,DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS BluetoothDevice ( Device VARCHAR , Address VARCHAR , Date VARCHAR);");
        
        }
        public List<BluetoothDevice>  getItemFromDatabase(SQLiteDatabase sqLiteDatabase) {
            List<BluetoothDevice> result = new ArrayList<>();
            // query database elements
            Cursor c = sqLiteDatabase.rawQuery("Select * from BluetoothDevice;", null);
        
            while (c.moveToNext()) {
                Date v = new Date();
                v.setTime(c.getInt(c.getColumnIndex("Date")) * 1000);
                Date date = new Date();
                date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));
                result.add(
                        new BluetoothDevice(
                                c.getString(c.getColumnIndex("Device")),
                                c.getString(c.getColumnIndex("Address")),
                                date
        
                        )
                );
            }
            c.close();
            return result;
        }
        
        public void store(List<BluetoothDevice> data,SQLiteDatabase sqLiteDatabase) {
            for (BluetoothDevice value : data) {
                String s = String.valueOf(new Date().getTime());
                //insert in database
                sqLiteDatabase.execSQL("INSERT INTO  BluetoothDevice VALUES(?,?,?,?);", new String[]{value.name, value.address, s});
        
            }
        }
        
        
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        
        }
    
    }

1 个答案:

答案 0 :(得分:1)

首先获取日历实例。然后用它来抽出时间。

Calendar today = Calendar.getInstance();

然后使用日历实例中的getmethod来获取当前时间。然后使用下面提到的数据库方法替换您的查询和选择参数。

get(Calendar.HOUR_OF_DAY): 0 to 23
get(Calendar.MINUTE): 0 to 59
get(Calendar.SECOND): 0 to 59

public Cursor getInformation(SQLiteDatabase db,string date){
    Cursor cursor;
    String[] projections={NAME.OF.COLUMNS.YOU.WANT1, NAME.OF.COLUMNS.YOU.WANT2};
    String selection=COLUMN.NAME.OF.DATE+" LIKE ?"
    String[] selection_args={date};
    cursor=db.query(TABLE_NAME,projections,selection,selection_args,null,null,null);
    return cursor;
}