Retrieving data given month wise - android

I am storing some data and date that is selected by user in sqlite in dd-MMM-yyyy format in storeDate named column with TEXT type because afaik there is no DATE type directly. Now I want to retrieve the stored data month wise. Suppose I give input as 01-Dec-2013 and build where clause, then I need to get the data of that particular month(Dec, 2013). Can someone Please suggest how to achieve this? My current query is:
Cursor cursor= db.rawQuery("SELECT * FROM "+TABLE_NAME+" "+whereClause+" GROUP BY "+CATEGORY, null);
What should be given at the place of whereClause?

SQLite does not support month names, sadly. You will have to convert it to a month name either using a lookup table, a case statement, or a switch on the presentation layer.
Try this
SELECT strftime('%Y-%m', table_column) FROM `table name` WHERE strftime('%Y-%m', table_column) = '2013-04'
If you want to print the month name only then try this
SELECT case strftime('%m',date_column) when '01' then 'January' when '02' then 'Febuary' when '03' then 'March' when '04' then 'April' when '05' then 'May' when '06' then 'June' when '07' then 'July' when '08' then 'August' when '09' then 'September' when '10' then 'October' when '11' then 'November' when '12' then 'December' else '' end
as month FROM `your_table` WHERE strftime('%m',date_column)='12'
Also take a took at this stuff for more date and time functions in SQLite
Date And Time Functions

You could use MySQL's MONTH() function
SELECT * FROM tbl WHERE MONTH( trans_date ) = 3

Related

Comparing dates in android sqlite database

I'm comparing two dates in android sqlite database
I stored dates in the format
YYYY-MM-DD
Cursor cursor=db.rawQuery("SELECT * FROM "+tableName+" WHERE SALESDATE BETWEEN '2020-1-01' AND '2020-2-01';",null);
It gives result with dates of month 10, 11 and 12 along with the dates between above specified dates.
I would like to know if it is a bug or is there any mistake in my code.
The problem here is that your date literals are in a non standard (and likely incorrect) format. Appreciate that the following inequality holds true:
'2020-10-01' > '2020-1-01' AND '2020-10-01' < '2020-2-01'
This is true because the text 10 is lexicographically larger than just 1, but also less than 2. To avoid this problem, use proper date literals:
String sql = "SELECT * FROM " + tableName + " WHERE SALESDATE BETWEEN '2020-01-01' AND '2020-02-01';"
Cursor cursor = db.rawQuery(sql, null);
Note that SQLite does not actually have a formal date type. Thus, it is very important to always store your dates in SQLite using a proper ISO format.
You should store your Date as long value in database. Simple new Date().getTime() gives you this value and new Date(long value) returns it back. So you can make such queries easy.
But what I can suggest is to:
Export your table to CSV,
Change the date values to a proper SQLite TimeString and
Re-import the CSV after deleting the original table.
Then, you can run a query like:
SELECT * FROM tableName WHERE SALESDATE BETWEEN '2020-01-01 00:00:00' AND '2020-02-01 23:59:59'

Android: SQLite Getting all records that inserted in last 7 days

Cursor cursor = db.rawQuery("SELECT * FROM expenses WHERE expense_date > (SELECT DATE('now', '-7 day'));", null);
I have this above query to get all records that inserted in last 7 days. But as a result of this query i am getting all the records. The date column of these records is inserted via Android's DatePicker and they are in 30-Jul-2015 format. I guess that's why this query does not work properly. Is there a way to make them consistent to get this query work properly or i am missing out something else ? Any help would be appreciated.
I've never tried using the SQLite built in date functions. Taking a quick look at the SQLite date function documentation here, it would seem that to use them the date needs to be in the format YYYY-MM-DD, which would be why your query is failing.
You can do some string manipulation/formatting before saving to the db and use that format.
Personally, I usually format in that manner but without the dash separators, then a simple less than/greater than comparison can be used, treating the date like a regular number. Of course some conversion back and forth is necessary for display, but for under the hood it works great.
int now = 20150730;
String query = "SELECT * FROM expenses WHERE expense_date > '" + now-7 + "'";

How to get week dates in SQLite database

I am developing android application. One of my application table has "foo_date" as column name. and data type is TEXT. I have following data in my table
primary key | foo_date | foo_value
--------------------------------------
1 2013-3-1 100
2 2013-3-2 2
3 2013-3-4 100
4 2013-3-3 1000
my requirement is to get data for the current week(i.e. 2013-3-4 to 2013-3-10). When i write below query, i am getting all data except row # 3
select * from foo_tbl where foo_date between '2013-3-4' and '2013-3-10';
How do I write sqlite query so that it includes all data for current week?
Thansk
Chintan
Your problem is that you have stored the dates in a format that cannot be compared easily; the character 1 comes before 4, so 2013-3-10 compares less than 2013-3-4.
As documented, you should use the ISO date format yyyy-mm-dd. With constant field sizes, you can use a query with string comparisons that work:
SELECT * FROM foo WHERE foo_date BETWEEN '2013-03-04' AND '2013-03-10'
or use a date function to compute the week:
SELECT * FROM foo WHERE strftime('%W', foo_date) = '09'
First, store the dates as standard sqlite time string format (i.e. YYYY-MM-DD).
Then, you can use this:
select * from foo where strftime('%W', foo_date) == strftime('%W', 'now')
to select the rows with the same week number as now.

Android: Save date normally to sqlite but sort by date considering month and day

I have seen number of post about storing date.
I am still not getting the fine and exact approach about saving it to a sqlite database.
I am able to store it, but during sorting I need to consider only month and day just like birthday where years doesn't matter.
What will be the query if I want to get the row whose date is 2 or 3 days in advance, like 2nd march row if searched on 28 Feb?
You should start by checking out the SQLite documentation of date & time functions.
For instance, to solve your problem "And what will be the query if i want to get the row whose date is 2 or 3 days in advance" you'd use julian day calculations, such as this example that you can execute directly in the sqlite3 shell:
create TABLE example (_id INTEGER PRIMARY KEY NOT NULL, date TEXT NOT NULL);
insert into example (date) values ('2011-01-02');
insert into example (date) values ('2011-04-02');
insert into example (date) values ('2012-02-26');
insert into example (date) values ('2012-02-27');
insert into example (date) values ('2012-02-28');
insert into example (date) values ('2012-02-29');
insert into example (date) values ('2012-03-01');
insert into example (date) values ('2012-03-02');
insert into example (date) values ('2012-03-03');
select date from example where julianday(date) - julianday('now') < 3 AND julianday(date) - julianday('now') > 0;
This would return (given that "today" is feb 28th) all the days that are one, two or three days in the future:
2012-02-29
2012-03-01
2012-03-02
Edit: To only return rows, regardless of year, you could do something like this - using a VIEW (again, exampl is directly in SQLite):
create view v_example as select _id, date,
strftime("%Y", 'now')||'-'||strftime("%m-%d", date) as v_date from example;
This VIEW would return the date & times in your database "rebased" on the current year - which, of course could introduce all manner of wonky behavior with leap years.
You can select all the dates like this in that case:
select date from v_example where
julianday(v_date) - julianday('now') < 3 AND
julianday(v_date) - julianday('now') > 0 ORDER BY v_date;
Which would return:
2012-02-29
2012-03-01
2001-03-01
2012-03-02
2010-03-02
If you want to sort by day and month consider storing the date as string in the format ddMMyyyy (you need two digits for day and month, otherwise the sorting will be flawed). Sorting by increasing values will give you dates sorted by day and month (and then year).
You can even do range query with string but you have to compute the query string.
Alternatively you may store the date as milliseconds in an additional column (this is the usual format for dates in the database) and do the range queries more easily with integer arithmetic.
One option is to use strftime() in SQLite to strip of the year and then do a comparison.
select * from sometable where strftime('%m-%d', somecolumn) = '02-28'
This will do a query of all rows for February 28th. But performance might be hurt if you have a large table and need to do a string conversion of every row for comparison. Maybe store the day and month in two additional columns if this query is performed often?

SQLite ORDER BY month number in a 'yyyy-mm-dd' format

I have a table with a column named call_date in the DATETIME format.
In this column I have the following date in this format yyyy-mm-dd.
What I want is to select the rows ordered by the month number in the column's value String.
Is there such SQLite function that does that??
I already tried strftime('%m', call_date) but ditn't work.
Thanks.
select * from myTable order by CAST(strftime('%m', call_date) AS INTEGER);
You can use strftime to get the month number and then order by that:
select ...
from your_table
order by strftime('%m', call_date)
In general I would try to avoid to order a result set by a calculated expression due to possible performance penalty. I would use an alternative approach: for example I would add MONTH column into the table and define a TRIGGER which will set the new column value. Then in queries you can order by a new column.

Categories

Resources