Sqlite comparing now to datetime is comparing date only - android

I am using sqllite for android and I have a the completedDate in the db in the following format
2012-06-26 17:20
I am trying to get the all the rows of the Task table whose completed date is in the future (greater than now)
I do this
select * from Task where completedDate > datetime ('now')
The problem is that the comparison seems to be based on date only without the time stamp. I am getting all the rows with completed date that is starting from tomorrow. However if it is the date as today (regardless of the time) then I don't get the row
Why is that? Any pointet

I found the solution in case anyone is interested.
Create a String representation of current date and do the comparison with it like the following
Date d = new Date();
String dStr = ..... //convert d to string using using simple date formated
select * from Task where completedDate > dStr

Related

How to query if the day of the start date > the day of the end date?

I use LocaleDate.now in Android to get data from Sqlite based on the start date of week and the end date of the week. For example, if start date is 20/07/2020, then the end date will be 26/07/2020. I will get data from range date betwwen 20/07/2020 and 26/07/2020. My code run fine until today, i get start date of this week is 27/07/2020, the end date is 02/08/2020. I surprised because i couldn't get the data from sql, so i debugged and i realized the Sqlite couldn't get the data from range date between 27/07/2020 and 02/08/2020. I think if the day of start date(27) > the day of the end date(2) then Sqlite can't query it. How to solve this problem?
SELECT name
FROM date_detail
where date BETWEEN '27/07/2020' and '02/08/2020'
//not show me anything
I think you can solve this problem by saving dates into database in another format, such as 'yyyy-mm-dd' or with timestamp, so it can select dates between two dates.

Sort a column with string format dd/MM/yyyy in SQLite (Android)

I have an SQLite database in an Android project with a Date column that stores the date-time as String in dd-mm-yyyy HH-mm-ss format. I need to sort it based on the descending order of the date.
Or, convert it to the standard yyyy-MM-dd HH-mm-ss format and then sort it.
The general ORDER BY DATETIME(coulmn_name) doesnt work.
NOTE:
This is not a duplicate question, other answers advice to change the database schema (Which is not possible, because I have data stored already)
I would like to suggest an alternative approach to the one you are taking. I personally ran into the same issue and solved it by not using a string date at all.
Instead i converted the date to epoch milliseconds ie unix timestamp and saved that. Then a sort is a simple order by the timestamp.
You can use the following approach:
SimpleDateFormat sdf = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
Date currentDate = sdf.parse(yourdatestring);
//Get the calendar in the time zone you need, generally it works off the bat with the default time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("yourtz"));
cal.setTime(currentDate);
//Get the milliseconds since epoch time
long millis = cal.getTimeInMillis();
You can save this timestamp and easily sort it. It'll be more accurate and easy to use than a string and potentially gives you the ability to handle different time zones.
You can retrieve the date by setting this timestamp directly in the calendar and getting a date from it
cal.setTimeInMillis(timestamp).getTime();
Hope this helps

Sqlite date format in my app

I am storing date and time in sqlite as timestamp value e.g. 1486650099741 when i use it in my code using setTimeinMillis for GregorianCalendar it converts perfectly. However when i try to year for the same time (in millis) using strftime ('%Y',datetimestamp) in sqlite it gives me weird results (year is shown as 1698 and not 2017)
is it something to do with the epoch (used by sqlite) ?
Please try this select strftime('%Y', datetimestamp/ 1000, 'unixepoch');

SQLite isn't returning correct records based on a date

I have four buttons on an android app i'm making.
Each button queries an SQLite database and grabs records based on a date. (Buttons are 'Today', 'Week', 'Month', 'All')
The date is stored as a DATETIME in my table, and i'm querying it with a date as well. Everything works well, until i'm grabbing everything that's been done ahead of the previous month.
Example
Todays date is June 29th 2016
I create an entry on June 16th 2016 into my SQLite Database and it stores successfully. I create another entry on June 27th 2016 and it stores successfully.
Now I press the 'Today' button and return 0 records. (Correct)
I press the week button and return 1 record (Correct - Created on June 27th)
I press the month button and return 0 records. (Incorrect. I should be getting 2 records)
The Code
This is the query I use for my database:
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= '" + date + "' ORDER BY created_at ASC"
The 'date' is calculated like so:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -31);
Date fromDate = cal.getTime();
date = dateFormat.format(fromDate);
(31 represents the largest possible number of days in a month period)
It seems that the problem occurs when the date goes back a month. If I remove 20 days instead of 31, the date will "June 9th" and i will receive BOTH records as i should. But if the date goes into May, i will receive 0 records.
Other queryStrings i have tried
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= date('now','-31 days') ORDER BY created_at ASC"
This didn't seem to work?
I'm still new to Android so apologies if it's a bad question. I have googled around but haven't found anything that might help.
UPDATE: Extra Info
Here is some additional code that might be more helpful
The dateFormat used to time stamp entries into my SQLite is:
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy - HH:mm", Locale.getDefault()); //"yyyy-MM-dd HH:mm:ss" - "dd-MM-yyyy HH:mm:ss"
Date date = new Date();
return dateFormat.format(date);
}
The date format used when i'm querying my database is:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
I'm not sure if this is correct, however my reasoning for leaving "HH:mm" off was due to the "Today" option not working correctly as it would return everything greater than the current time (which is obviously nothing in terms of time stamping)
Unable to solve...Ended up converting my database DATETIME to INTEGER and storing the date in milliseconds then just converting between date format and milliseconds to query and display information.
If you want to alter the month of a Java Calendar object you will need to use:
cal.add(Calendar.MONTH, -1);
where the above snippet would roll the month back by one. If you call cal.add(Calendar.DATE, -31) on February 15, for example, you get a weird result because the month won't change but the day will roll over.
Update:
You also have to make sure that the date format you feed into MySQL is correct. MySQL expects the format YYYY-MM-DD for dates, so use this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(cal.getTime());
I recommend using JodaTime if you expect complex calendar operations.

Sqlite: select ('now') not works as expected

I want to get the current date as yyyy-MM-dd from SQLite, I use the following query:
***SELECT date('now')***
But instead of returning the current date, it returns the next day from today.
For example, today (2015-12-01) I run the query and it returns (2015-12-02).
What I did wrong?
Image running query + calendar
sqlite date and time functions use UTC time zone internally. In UTC the date was already 2015-12-02.
If you want to use another timezone, you need to specify it explicitly, e.g.
select date('now','-05:00');
I'd suggest to use UTC millisecond timestamps in your database layer though and have the presentation logic such as date formatting with timezone adjustment in your app code.
Reference: https://www.sqlite.org/lang_datefunc.html

Categories

Resources