简体   繁体   中英

Deleting rows from SQLite (Android) based on time

I've seen some similar questions on here, but none of them are helping so I figured I see if I could get some personalized help. I'm adding things to my database with a column called 'time_added' which is in the form:

2011-12-20 09:55:28

I am then calling a method I wrote to delete based on time, currently I just want it to delete everything before now:

StringBuilder queryString = new StringBuilder("date('now') < date('");
queryString.append(KEY_TIME).append("')"); //.append("','+0 days')");
int c = mDatabase.delete(DATABASE_TABLE,  queryString.toString(), null)

So right now it prints a WHERE clause that says:

date('now') > date('time_added')

I thought this meant that everything that is before now will be deleted, but maybe I am wrong. Thanks for the help.

I remember having some trouble implementing this too. I don't remember why, but the date command didn't seem to cooperate. I just used a string comparison on the date format. Here's the code that I ended up using. It seems to work fine.

    // Range to cleanup anything in the DB that is older than 2 days
    //
    // NOTE: This value must be negative so that when it gets added to the
    // current date, it sets the range as anything older than 2 days ago
    int rangeInDays = -2;

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Calendar range = Calendar.getInstance();
    range.add(Calendar.DAY_OF_MONTH, rangeInDays);

    int numDeleted =
        mDatabase.delete(DATABASE_TABLE, "time_added" + " < '"
                    + dateFormat.format(range.getTime()) + "'", null);

I would store your dates as integers using getTimeInMilliseconds() . It makes comparisons easier and means you do not need to worry about international date formats.

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