Reputation: 1736
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?
Upvotes: 1
Views: 364
Reputation: 180030
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);
Upvotes: 1
Reputation: 1716
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.
Upvotes: 1