Best way to work with dates in Android SQLite

Filipe picture Filipe · Sep 9, 2011 · Viewed 193.8k times · Source

I'm having some trouble working with dates on my Android application that uses SQLite. I have a couple questions:

  1. What type should I use to store dates in SQLite (text, integer, ...)?
  2. Given the best way to store dates how do I store It properly using ContentValues?
  3. What's the best way to retrieve the date from the SQLite database?
  4. How to make a sql select on SQLite, ordering the results by date?

Answer

PearsonArtPhoto picture PearsonArtPhoto · Dec 4, 2012

The best way is to store the dates as a number, received by using the Calendar command.

//Building the table includes:
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_DATETIME+" int)");

//And inserting the data includes this:
values.put(COLUMN_DATETIME, System.currentTimeMillis()); 

Why do this? First of all, getting values from a date range is easy. Just convert your date into milliseconds, and then query appropriately. Sorting by date is similarly easy. The calls to convert among various formats are also likewise easy, as I included. Bottom line is, with this method, you can do anything you need to do, no problems. It will be slightly difficult to read a raw value, but it more than makes up that slight disadvantage with being easily machine readable and usable. And in fact, it is relatively easy to build a reader (And I know there are some out there) that will automatically convert the time tag to date as such for easy of reading.

It's worth mentioning that the values that come out of this should be long, not int. Integer in sqlite can mean many things, anything from 1-8 bytes, but for almost all dates 64 bits, or a long, is what works.

EDIT: As has been pointed out in the comments, you have to use the cursor.getLong() to properly get the timestamp if you do this.