我有一个名为 daily_mood 的表格,它有三(3)列,如下所示:
CREATE TABLE daily_mood (moodid INTEGER PRIMARY KEY autoincrement,mood TEXT,mooddate DATETIME)
它的数据看起来像这样:
现在,我想根据mooddate列选择/删除从当前日期到24小时之前的所有行。
我尝试过这样的查询:
SELECT *from daily_mood where mooddate>=datetime('now', '-1 day');
结果应该是来自上面数据的1行(最后一行)。但这里是2.like
结果应该是最后一行。有人可以帮帮我吗?感谢。
答案 0 :(得分:4)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
Calendar c = Calendar.getInstance();
c.setTimeMillis(System.currentTimeMillis());
c.add(Calendar.HOUR_OF_DAY, -24);
String query = "SELECT * from daily_mood WHERE mooddate >= " + "'" + dateFormat.format(c.getTime()) + "'";
答案 1 :(得分:1)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
Calendar cd = Calendar.getInstance();
Calendar removeBefore = Calendar.getInstance();
removeBefore.set(cd.get(Calendar.YEAR), cd.get(Calendar.MONTH),(cd.get(Calendar.DAY_OF_MONTH) - 7));//Here set day before old data to be removed.
try{
sqlDatabase=getSqlWritable();
rowaffeted=sqlDatabase.delete(TB3, TB3_Date +" < ? ", new String[]{df.format(removeBefore.getTime())});
}catch(Exception e){
e.printStackTrace();
}
//您需要使用以下方法
public SQLiteDatabase getSqlWritable(){
if(dbhelper == null)
dbhelper=new DbOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
return dbhelper.getWritableDatabase();
}