I have a requirement, wherein column having date time information must be compared against present date & time. If earlier then this particular record must be deleted.
I have progressed with below implementation, but not getting any error & expected behavior is not met.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault());
Calendar nowCalendar = Calendar.getInstance();
String strNowTime = dateFormat.format(nowCalendar.getTime());
// Delete the records at Manager_Dashboard SQLiteDB
String whereClause = "DATETIME(End_Time) < DATETIME(?)";
String whereArgs[] = {strNowTime};
dbOfflineRange.delete("Offline_Range",whereClause,whereArgs);
As you could notice, if I have a record with End_Time in text within SQLite table (as 30 Nov 2018 21:35), then this should be compared against current datetime (as 30 Nov 2018 23:35)
As End_Time being earlier than Now, I am expecting deletion. But its not happening.
The Date and Time SQL functions require the date to be in a recognised format.
Time Strings A time string can be in any of the following formats:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
SQL As Understood By SQLite - Date And Time Functions
Your best(simplest) option would be to store them as YYYY-MM-DD HH:MM (i.e. change the SimpleDateFormat accordingly).
Note you would not even need the datetime function as direct comparison of the values would result in the desired outcome.
Storing the unix timestamp value would be the more efficient storage/processing time wise.
You can then use the strftime function to return the date in the format you wish.
Otherwise you can convert the store value to a recognised format using SQL functions such as substr and then do the comparison.
SQL As Understood By SQLite - Core Functions
here's an example of how you could handle data stored in DD MMM YYYY HH:MM format
assuming that the value to compare against is provided in YYYYMMDDHH:MM format :-
DROP TABLE IF EXISTS Offline_Range;
CREATE TABLE IF NOT EXISTS Offline_Range (end_time);
-- Add some test data dd MMM yyyy HH:mm
INSERT INTO Offline_Range VALUES
('21 May 2018 10:30'),
('21 Jun 2018 10:30'),
('21 Jul 2018 10:30'),
('21 Aug 2018 10:30')
;
SELECT * FROM Offline_Range
WHERE
substr(end_time,8,4)||
CASE
WHEN instr(end_time,'Jan') THEN '01'
WHEN instr(end_time,'Feb') THEN '02'
WHEN instr(end_time,'Mar') THEN '03'
WHEN instr(end_time,'Apr') THEN '04'
WHEN instr(end_time,'May') THEN '05'
WHEN instr(end_time,'Jun') THEN '06'
WHEN instr(end_time,'Jul') THEN '07'
WHEN instr(end_time,'Aug') THEN '08'
WHEN instr(end_time,'Sep') THEN '09'
WHEN instr(end_time,'Oct') THEN '10'
WHEN instr(end_time,'Nov') THEN '11'
WHEN instr(end_time,'Dec') THEN '12'
END
||
substr(end_time,1,2)||substr(14,5)
<
'2018062200:00' -- 22 Jun 2018 00:00 amended to suit i.e. the value input
This creates a table :-
The result from the query would be :-
Related
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.
My query:
SELECT * FROM table_event WHERE event_start_date>datetime('Oct 4, 2015 12:00:00 AM')
You need to save the date in the form YYYY-MM-DD HH:MM:SS or in millisecond difference to compare it in the sqlite.
I have stored dates' date as String in my database in the following format :
dateFormater = new SimpleDateFormat("dd MMM yyyy");
Now i need to access data between the two dates startWeekDate and endWeekDate both formatted as above. Currently , the where clause of my query is :
at_date BETWEEN Datetime( '"+startWeekDate+"') AND Datetime( '"+endWeekDate+"')
Where startWeekDate is '10 Aug 2014' and endWeekDate is '16 Aug 2014'. But I am getting the null result on my TextView. Can any one guide me how can i do this.
This is not one of the supported date formats.
Just use yyyy-MM-dd.
I'm running ORMlite on Android app. I have created a #DatabaseTable class with a Timestamp field.
#DatabaseTable
public class Cliente {
#DatabaseField
private Timestamp dateinicio;
}
I can insert items but when I try to recover data I get this error:
java.sql.SQLException: Could not assign object 'Wed Jan 29 13:35:01 CET 2014'
to field FieldType:name=dateinicio,class=Cliente
I suppose this must be a typical error but I cannot resolve it.
Is this existing data you are trying to get to work or did ORMLite store this date for you? Either way you are going to have to match the formats that Sqlite supports.
Internally ORMLite uses "yyyy-MM-dd HH:mm:ss.SSSSSS". You can specify the format using something like the following where the ... is replaced with the format which matches your data.
#DatabaseField(format = "...")
private Timestamp dateinicio;
Sqlite officially supports the following date formats.
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
See this answer here: ORMLite query date format issue
I am working on android project. I am setting date and time but it is displaying in the following format.
Mon Nov 19 11:00:00 GMT+05:30 2012
In my database table the datetime column datatype is datetime. So how can I change the above output to datetime format to store it in database.
Any help in this regard will be thankful.
you should probably read a bit about SimpleDateFormat, it's the way to parse String into Date.
the way to do this is to create a pattern for the formatter, then create the formatter and after that parse the Strings.
String pattern = "EEE, dd MMM yyyy HH:mm:ss z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date myDate = format.parse(str);