1

I am working on a project and now I have been stuck on a weird stage.

I know that we can execute any query that has to do anything with database we can write that using:

Cursor cursor = db.rawQuery("SELECT * FROM table_name", null);

But now I want to execute this query:

"SELECT strftime('%s','now','-2 day')"

Generally the above query returns unixepoch time of one day before yesterday.

Does anyone know how can I get this done?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
activesince93
  • 1,716
  • 17
  • 37

2 Answers2

1
Date date = new Date();

will return the current day, if you then subtract X numbers of days, then parse that Date to String with the required format. You can do this with the method SimpleDateFormat:

String newDate = new SimpleDateFormat(pattern).format(date);

where pattern can be something like this "dd-MM-yyyy"

Then, you can add said date to your query.

Waclock
  • 1,686
  • 19
  • 37
  • Since we can execute any SQLite query, I am just curious about this query, How can I execute these types of queries that doesn't have to do with database? You can check this link https://www.sqlite.org/lang_datefunc.html – activesince93 Oct 02 '15 at 06:10
1

You would handle this query like any other query:

Cursor cursor = db.rawQuery("SELECT strftime('%s','now','-2 day')", null);
try {
    if (cursor.moveToFirst()) {
        long seconds = cursor.getLong(0);
        ...
    } else {
        // cannot happen with this query
    }
} finally {
    cursor.close();
}

If you want to access the column by name (which is completely pointless if you have only a single column), you can give it an alias:

cursor = db.rawQuery("SELECT strftime(...) AS s", null);
cursor.getColumnIndexOrThrow("s");  // returns zero
...

Please note that for queries that return a single value, there is a helper function:

long seconds = DatabaseUtils.longForQuery(
                   db, "SELECT strftime('%s','now','-2 day')", null);
CL.
  • 173,858
  • 17
  • 217
  • 259