SQLite Date Query In Android - android

I am using SQLite database for my application.
The Table Structure Goes Like :
_id : integer primary key
name : text
day : date
I am able to store date in format : dd-mmmmm-yyyy eg. 15-June-2011
But when i tried to retrieve all records filtered by date from the database it returns me null.
database.query(DATABASE_TABLE, new String[] { "strftime('%d-%mm-%Y',date('now'))","strftime('%d-%m-%Y',"+KEY_DAY+")" },
"strftime('%d-%m-%Y',date('now'))=" + KEY_DAY , null,null,null,null,null);
It didnt match with anyrow's date even though there were some matching dates.
I have already gone thru documentation of SQLite. But didn find any solution yet.
I want to have something like :
select * from table where day=curdate();
How can i do the same task in SQLite ?.
(Yes I am flexible to change the format of date stored in Dateabase)
What are other alternatives for the same task ?.

In java programming you can convert any date format into long (time in milliseconds) and viceversa. My opinion is while storing format the date into long format in java and then store long value of date in database. also while retrieving you can retrieve the long value and then format that as per your expected date format. I have been using this type of logic for several application.
Thanks
Deepak.

The function strftime('%d-%m-%Y',date('now')) returns a string with the month in numeric format (from 01 to 12). As far as I can tell from the docs, there is no format specifier to return the full name of the month.
I think you'll have to store your dates using numerical month specifiers instead of names.

Related

CONVERT(varchar, COLNAME, 120) doesn't work in sqlite java

So I'm trying to query all the same dates but this code won't work
SELECT * FROM schedTBL WHERE CONVERT(varchar, DueDateTime, 120) LIKE " + "'%"+ text + "%'"
it returns no such column:varchar
This looks like a SQL statement for SQL Server, not SQLite...
Assuming you are storing dates in field DueDateTime without the hour part, something like this should do:
SELECT * FROM schedTBL WHERE DueDateTime = '2016-09-24'
Or you'll need like if you also have hour values. That depends on how you are actually storing dates/times in your SQLite DB.
Try formatting the date in Java and send it as a parameter to your query.
SQLite doesn't handle dates like SQL Server.
See:
SQLite Date And Time Functions
In SQLite, date values would be formatted with the strftime() function, or for this particular format, with the date() function:
... WHERE date(DueDateTime) LIKE ...
But this works only for supported date formats.
If the values in your database use an unsupported format, your only choice is to convert them, or to try to match the actual string:
... WHERE DueDateTime LIKE ...

How to sort table row based on Specific Column and Month in Android SQLite? [duplicate]

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?
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.
SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.
Any value stored in the SQLite database has one of the following storage class:
NULL
INTEGER
REAL
TEXT
BLOB
so I am not sure what you meant by but the date is stored as a long, unhelpful integer.
For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.
I hope this helps.

Android SQLite RawQuery not returning records with 2017 date

I have a database that contains upcoming births. The file has 5 records in it with due dates of (11-15-2016,10-15-2016, 12-14-2016, 12-13-2016 and 02-12-2017)
The query is
SQLiteDatabase db = dbhelper.getReadableDatabase();
String QueryPart1="SELECT inseminations._ID, inseminations.patient_id, inseminations.date_due ";
String QueryPart2="FROM inseminations ";
String QueryPart3="WHERE inseminations.date_due>=? ";
String QueryPart4="ORDER BY inseminations.date_due ASC";
String FinalQuery=QueryPart1+QueryPart2+QueryPart3+QueryPart4;
mCursor = db.rawQuery(FinalQuery ,howToFilter);'
howToFilter is
String howToFilter[]={ExpectedDateDue};
ExpectedDateDue is
ExpectedDateDue = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
The query retrieves all records except for the one from 2017, the listview is sorted correctly, it's as if the query is only taking those records where the month is after the current month instead of the entire date.
Comparison operators on text in SQLite use lexicographic order. What this means, for example, is "01-01-2017" is less than "05-04-2016". SQLite has no indication that these strings represent moments in time that should be compared chronologically.
In general, I dislike using strings for timestamps in my databases for reasons like this. I much prefer to store timestamps as long values representing seconds (or milliseconds) since epoch. It's far easier to compare timestamps this way, and converting to and from date strings is simple enough either in SQLite or in Java.
If that's not feasible for some reason, then I suggest you alter the way you store your date strings in the database. Instead of MM-dd-yyyy, use yyyy-MM-dd. In this format, lexicographic comparisons will work; using the same example as before, "2017-01-01" is greater than "2016-05-04". Additionally, this format is acceptable as input to SQLite's various date and time functions, should you decide to use them.
If you can't alter the way the dates are stored, you will need to somehow convert them into a format that is comparable in the way you expect. You could use SQLite's substr() and || (concatenation) functions in the query to convert the date from MM-dd-yyyy to yyyy-MM-dd format. The code in this answer demonstrates this.

Datetime aritmethics in sqlite on android

I am trying to do some datetime aritmethics in Sqllite. I have a table with two rows defined as type DATETIME. These fields are called LOG_FROM and LOG_TO. In a query on this table I try to do the following:
SELECT SUM(LOG_FROM - LOG_TO) AS TIMESPENT FROM LOG_TABLE WHERE X=Y;
This subtraction inside the SUM function does not work as intended. It will always return the number 0. I read the data via a cursor.getString.
When I store dates in the table I convert them to strings on the format yyyy-MM-dd HH:mm:ss
SQLite ignores column data types. Your date strings are strings.
Your date format is supported by the built-in date functions, so you can use them to convert the dates to numbers.
Assuming that you want the result to be a number of days, use julianday:
SELECT SUM(julianday(LOG_TO) - julianday(LOG_FROM)) ...

Format integer to formatted date in an SQLite select statement

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?
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.
SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.
Any value stored in the SQLite database has one of the following storage class:
NULL
INTEGER
REAL
TEXT
BLOB
so I am not sure what you meant by but the date is stored as a long, unhelpful integer.
For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.
I hope this helps.

Categories

Resources