简体   繁体   中英

Android SQlite: Querying table rows by date range from today backwards?

I get a date from the server in "MM/dd/yyy" form, then I convert it into milliseconds using the following function:

public static long getSimpleDateToMillis(String simpleDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date date = formatter.parse(simpleDate);
        return date.getTime();
}

Then afterwards I save the result into the database as int.

Right now I'm stucked in what seems like a dead-end for me. I can't find a way through searching and from my stock knowledge on how I would be able to filter my cursorloader by project_date column which is saved as integer in the database.

In what way would I be able to query such that it would: Select all row from projects table where the project_date is today and backwards (yesterday and so on).

I tried this one but seems to be really not the answer.

String [] projection = new String []{};
        String selection = "datetime("+ ProjectsEntry.COLUMN_PROJECT_DATE + "/1000, 'unixepoch') =? ";
        String [] selectionArgs = new String[]{" date('now')"};
        return new CursorLoader(this,
                JobsContract.JobsEntry.CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                null);

I haven't found any other reference that would point me, so I'm hoping someone might also have encountered this perhaps.

This is how I do something quite similar, but using full timesteamp ie long rather than int.

First I have this method to get the TimeStamp, to get today's date/time as of midnight (bar 1 millisecond):-

/**
 *
 * @return  1 millsecond before midnight today
 */
private long getDateTimeOfAllofToday() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH,1); // tomorrow
    cal.set(Calendar.MILLISECOND,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.HOUR_OF_DAY,0);
    cal.add(Calendar.MILLISECOND,-1);
    return cal.getTimeInMillis();
}

Then I create the respective where clause eg :-

filter = DBRulesTableConstants.RULES_ACTON_COL +
        " <= " +
        Long.toString(getDateTimeOfAllofToday());

This is used via a rawQuery so not exactly what you want but easy enough to to change " <= " to " <=?" and then use String [] selectionArgs = new String[]{Long.toString(getDateTimeOfAllofToday())}; or a modified version to get integer.

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