I have an SQLite database within my Android application, which stores dates as integers. These integers are derived from a call to Java.util.Date.getTime();
. I am trying to run a raw query of my database to get a Cursor to pass to a CursorAdapter and display in a ListView, but the date is stored as an integer as returned by getTime()
.
To keep my program simple, I would like to avoid using a SimpleArrayAdapter, and stick with the CursorAdapter.
Is it somehow possible to format the integer within the date colum as mm-dd-yyyy
so that the column of the table, that the cursor is pointing to, contains properly formatted values rather than the integer that was returned by Java.util.Date.getTime();
when I added the item to the database?
Use the STRFTIME() function to format date\time\datetime data in SQLite. This function takes two arguments. The first argument is a format string containing the date/time part pattern. In our example, we use the format string '%d/%m/%Y, %H:%M'.
SQLite supports six date and time functions as follows: date(time-value, modifier, modifier, ...) time(time-value, modifier, modifier, ...) datetime(time-value, modifier, modifier, ...)
Using INTEGER to store SQLite date and time values First, create a table that has one column whose data type is INTEGER to store the date and time values. Second, insert the current date and time value into the datetime_int table. Third, query data from the datetime_int table. It's an integer.
Date and Time Datatype. SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values: TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.
SELECT strftime("%m-%d-%Y", date_col, 'unixepoch') AS date_col
Your code will work if it expects a result set column in that format called date_col.
EDIT: One thing you need to watch out for is that getTime uses milliseconds since 1970, while standard UNIX time (including SQLite) uses seconds.
The Java.util.Date.getTime();
method is returning an integer that represents the "unix time".
The simplest way to read this number as a date is by storing it as-is, and reading it using the following Sqlite query:
SELECT strftime('%m-%d-%Y', 1092941466, 'unixepoch');
which returns:
08-19-2004
If you need another format, you can use the strftime
function to format is as you like, or any of the other date formats and functions available.
You'll have to, as Matthew Flaschen points out in a commend below, divide the date by 1000 before you are able to use them in this way. "Real" unix times are measured in seconds since the epoch, and Java.util.Date.getTime();
returns milliseconds since epoch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With