Nomi
Nomi

Reputation: 21

Sqlite Query is not working properly

I have created a database with a String column which contains dates in String format (dd/mm/yyyy). I want to fetch the data from that table which is between two given dates, but when I tried with the below query, I found that it doesn't make any difference what month and year I have selected; it compares the "dd" field only from "dd/mm/yy".

The below query will display all the data which is between day 14 to 25 from every month and year. I want data between the given date, month, and year.

Select * from RunningLog 
where CAST(RunDate AS DATETIME) between CAST('14/04/2011' AS DATETIME) and 
      CAST('25/04/2011' AS DATETIME)

Upvotes: 0

Views: 417

Answers (4)

strongmayer
strongmayer

Reputation: 488

You can compute the number of seconds between two dates. Here is an example: SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');

Based on the sign of the difference you can say if one date is before another. In your case you have to do two comparisons, so you have to verify the sign of two differences. Here you can find other examples, maybe they give you other ideas (http://www.sqlite.org/cvstrac/wiki?p=DateAndTimeFunctions).

Upvotes: 0

Jack
Jack

Reputation: 9252

Please see my answer here about how dates are (or are not) stored in sqlite3. Sqlite doesn't have a date field, so its actually stored as a string. Trying to sort / filter on this will prove to be difficult. Instead use an int field, and store the time in milliseconds.

I prefer INTEGER / Unix time storage, then use the built in date and time functions to format when pulling from DB.

Example:

long millis = Calendar.getTimeInMillis();

Store millis in the database as an integer. Then, refer to the first link on how to use the date and time functions in sqlite3.

Upvotes: 1

sebastianf182
sebastianf182

Reputation: 9978

Recomendation: Use Datetime fields in the database and JodaTime as a Time library.

Is quite easy to parse the datetime into a DateTime object and then you have many useful methods to compare and work with dates.

Also, your SQL queries will be better.

Upvotes: 0

Cristian
Cristian

Reputation: 200150

Sqlite3 documentation does not say it can cast a datetime: http://www.sqlite.org/lang_expr.html (refer to Cast expressions numeral). Why don't you do that from Java? I mean, how are you storing the dates in the database? I highly recommend saving a long (Unix time); that way you can easily get a couple of long numbers that represent an exact date and time and use them to query your table.

Upvotes: 0

Related Questions