Reputation: 36374
I'm storing date in sqlite database in Android as this:
initialValues.put(KEY_TIME, time.getTime());
where time is an instance of Date (which has the correct time) and KEY_TIME is an integer column.
Once stored, when I retrieve it with a query such as this:
String selectQuery = "SELECT * FROM " + TABLE_NAME + " order by date(" + KEY_TIME + ") DESC" ;
I never get the data with the recent one first.
I get spurious time which is almost 40 years old. Where am I going wrong?
Upvotes: 0
Views: 1692
Reputation: 40315
java.util.Date.getTime()
returns the number of milliseconds since the start of 1970 (epoch time). SQLite can deal with Unix epoch time, which is the same value, but expressed in seconds (see java.util.Date.getTime()
).
The mismatch of seconds and milliseconds is the reason you are seeing incorrect dates.
You can divide the value by 1000 to get Unix style epoch time, and specify 'unixepoch' (see SQLite Time & Date Functions) to SQLite's date function, e.g.:
SELECT date(KEY_TIME / 1000, 'unixepoch') FROM TABLE_NAME
If you are using a java.sql.Date
it is the same (that class extends java.util.Date
).
However, as 323go mentioned in the question comments, just sort directly by KEY_TIME
, which will give you the sort order you are looking for.
Upvotes: 1