Comparing dates in android sqlite database - android

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'

Related

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 + "'";

Sqlite sorting by date column

I am storing date in ISO8601 format example 2015-04-15T10:54:14Z in sqlite table, I want youngest date from table. below are the dates in my sqlite table
2015-04-15T10:54:14Z
2015-04-15T10:54:115Z
2015-04-15T10:54:216Z
2015-04-15T10:54:320Z
2015-04-15T10:54:422Z
I am trying below query:
SELECT * FROM Table1 ORDER BY datetime("date_column") DESC ;
but I am not getting appropriate result.
ISO 8601 datetime stamps normalized to UTC have the nice property that the alphabetical (lexicographic) order is also temporal order.
You don't need the datetime(), you can just ORDER BY date_column DESC to sort them newest first, and you can add LIMIT 1 to get just the newest one.
Update your query to this:
SELECT * FROM Table1 ORDER BY date_column DESC LIMIT 1
use this method to put date column in your db:
public String getDatetime(){
//get time and date
Calendar c=Calendar.getInstance();
CharSequence s = DateFormat.format("yyyy-MM-dd HH:mm:ss", c.getTime());
//convert it to string array
return s.toString();
}
then use your query as you used before, cause datetime() accepts specific formatts.

Retrieving data given month wise

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

SQLITE DB sort query by string formatted date field

I have a SQLITE DB with a string field which contains a date in the following format: "01.01.2012".
What I want is to sort the by this string formatted date in a query.
I tried this without success:
SELECT * FROM fahrer, fahrzeuge, nutzungsarten, fahrtenbuch WHERE fahrtenbuch.nutzungsart_id = nutzungsarten._id AND fahrtenbuch.fahrzeuge_id = fahrzeuge._id AND fahrtenbuch.fahrer_id = fahrer._id ORDER BY strftime ('%d.%m.%Y', fahrtenbuch.startdatum)
What I am doing wrong?
The values in the startdatum column are not in a format that SQLite recognizes, so you cannot use it as a parameter to strftime.
(Even if it worked, the result would not be sorted correctly because that date format does not begin with the most significant field, the year.)
You could try to extract the date fields so that the sorting is equivalent with the yyyy-mm-dd order:
SELECT ...
ORDER BY substr(startdatum, 7, 4),
substr(startdatum, 4, 2),
substr(startdatum, 1, 2)
But I would recommend to convert the values into a supported format in the first place.

Using select method in SQL

I've added 3 strings of data into a SQL database in android. A fourth string makes up the database, however it is a date:
SimpleDateFormat outputDate = new SimpleDateFormat(yyyy-MM-dd)
Date outputDate = new Date();
When the user enters information to the database, the adding method for the database creates the date, which is added to the database.
My question is, how can I use these imported dates to create a method whereby only the rows in the database that were added on in the last 31 days?
A SELECT method comes to mind through research, but I don't know how to implement it?
Thanks
Presuming your database engine is SQLite, you should try something like that
SELECT * from your_table where julianday('now') - julianday(your_date_field)<=31;
You may be interested in SQLite date functions as well: http://www.sqlite.org/lang_datefunc.html
As long as you ask about Android I assume that the database you use is SQLite. SQLite does not have datatype for date. Thus you have couple of options: store the date in string (like you did) or store the timestamp of the date.
I seriously recommend you to use the second option as it is going to convert your dates in integers and it will be even easier to handle.
Thus when you want to select only events in the last 31 days you can do:
SQLiteDatabase database = helper.getWriteableDatabase();
final long millisIn31Days = 31 * 24 * 60 * 60 * 1000;
String where = "<your-date-column> >= ?"
String [] whereArgs = { String.valueOf(new Date().getTime() - millisIn31Days) };
Cursor cursor =
database.query("<TABLE_NAME>", null, where, whereArgs, null, null, null);
Note that here I write in angular brackets all the values you should actually fill in with the correct constants.
If you, however, want to stick to the string solution, you can still go with string comparison, as long as you specify the date format in correct manner (yours seems to be like that). In the string solution you will need to calculate the date of 31 days ago. You can use the Calendar's class auxiliary methods to achieve that.

Categories

Resources