views:

247

answers:

1

I understand that SQLite stores dates as long integers. When I read rows using the standard method (i.e. using the query() method that reads data into a cursor), the result is a date string that includes the time:

2010-05-25 19:52:04

If I want a different format, I have to parse the string back into a date - possible, but a bit backwards.

By using a ViewBinder (as suggested in this question), I can pretty much do anything I want, but the date is already a string at the time the overridden method executes.

The accepted answer to the above question also suggests that storing dates as longs would help avoid this problem. I don't want to do that, just in case I want to interpret my data with something else than this application. Maybe I want to expose it via a provider.

To make matters worse, a DateFormat instance obtained via

android.text.format.DateFormat.getDateFormat(getApplicationContext())

cannot parse such a date string that is returned by the cursor. There is actually no static method that can do that - it is a one-way transformation, apparently an oversight.

Is there a way to handle this in the database adapter instead, i.e. controlling the date format that the cursor contains, so that I don't have to change the schema, and don't have to parse the default output back into a Date type?

The answers so far suggest that I should do the output formatting in the database. I don't want to do that for multiple reasons, most notably because I cannot format dates based on the user's locale that way (not easily, that is).

+1  A: 

SQLite has a number of built-in date and time functions.

Doug Currie
I am using android.database.sqlite.SQLiteDatabase.query(), which expects a list of column names. Are you saying that I have to hand-code the query?
cdonner
@cdonner, yes, use android.database.sqlite.SQLiteDatabase.rawQuery().
Doug Currie
@cdonner, alternatively (and I can't test it since I don't have an Android platform at hand) I wonder what giving android.database.sqlite.SQLiteDatabase.query() a column name of "strftime('%Y-%m-%d',date_colname)" would do?
Doug Currie
If I use database functions, I will not get the date formatted in the user's locale (unless I somehow try to build a format string from the locale information). This is not a good idea.
cdonner
I have a working solution, i.e. parsing the data string back into a Date variable. It is a bit slow, though.
cdonner
The SQLite functions include julianday() which should eliminate the need for parsing.
Doug Currie