Android working with dates and SQLite - android

I am trying to create a simple reminder app. Im just logically thinking about the process. Basically I want to be able to choose a DAY and time e.g Monday 15:00, this will trigger EVERY Monday 15:00 until it gets deleted from database. Having said that example I have questions to accomplish this process.
How will I store DAY and TIME, what type, do I need different columns in my table?
How can I compare real time DAY to current DAY, so if its Monday real time it will return ONLY Monday reminders? is this possible?
Will I need to primarly focus using calendar?

As documentation says:
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values.
You can store date and time in the TEXT type of field in the following format:
YYYY-MM-DD HH:MM:SS.SSS
and then use built-in date & time functions of SQLite to filter your records.
Another option is to store date & time as a time-stamp in milliseconds and write proper queries for selecting data or use Joda library for filtering or date & time transformation, but probably such solution would be less efficient and less convenient than first option.

Using integer column is the easiest solution.
Just store the date in millisecond (Calendar.getTimeInMillis()) and your good to go.
Then you just have to search on that integer to find the correct event in your database :
String selectQuery = "SELECT whateveryouneed FROM events WHERE date_event > ?";
Cursor c = db.rawQuery(selectQuery, new String[] { String.valueOf(calendar.getTimeInMillis())});
...
if you need to find all the event for a day , you just have to find the limits of the day in millisecond and make a query according to those limits

Related

Android SQLite RawQuery not returning records with 2017 date

I have a database that contains upcoming births. The file has 5 records in it with due dates of (11-15-2016,10-15-2016, 12-14-2016, 12-13-2016 and 02-12-2017)
The query is
SQLiteDatabase db = dbhelper.getReadableDatabase();
String QueryPart1="SELECT inseminations._ID, inseminations.patient_id, inseminations.date_due ";
String QueryPart2="FROM inseminations ";
String QueryPart3="WHERE inseminations.date_due>=? ";
String QueryPart4="ORDER BY inseminations.date_due ASC";
String FinalQuery=QueryPart1+QueryPart2+QueryPart3+QueryPart4;
mCursor = db.rawQuery(FinalQuery ,howToFilter);'
howToFilter is
String howToFilter[]={ExpectedDateDue};
ExpectedDateDue is
ExpectedDateDue = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
The query retrieves all records except for the one from 2017, the listview is sorted correctly, it's as if the query is only taking those records where the month is after the current month instead of the entire date.
Comparison operators on text in SQLite use lexicographic order. What this means, for example, is "01-01-2017" is less than "05-04-2016". SQLite has no indication that these strings represent moments in time that should be compared chronologically.
In general, I dislike using strings for timestamps in my databases for reasons like this. I much prefer to store timestamps as long values representing seconds (or milliseconds) since epoch. It's far easier to compare timestamps this way, and converting to and from date strings is simple enough either in SQLite or in Java.
If that's not feasible for some reason, then I suggest you alter the way you store your date strings in the database. Instead of MM-dd-yyyy, use yyyy-MM-dd. In this format, lexicographic comparisons will work; using the same example as before, "2017-01-01" is greater than "2016-05-04". Additionally, this format is acceptable as input to SQLite's various date and time functions, should you decide to use them.
If you can't alter the way the dates are stored, you will need to somehow convert them into a format that is comparable in the way you expect. You could use SQLite's substr() and || (concatenation) functions in the query to convert the date from MM-dd-yyyy to yyyy-MM-dd format. The code in this answer demonstrates this.

Query unique date to cursor

In my database dates is stored in miliseconds as string. How to query unique dates considering only month and day and count how many date share same day?
Divide by 1000 to get seconds, then use the unixepoch modifier to get date, and use strftime to output only the year and month:
SELECT strftime('%Y-%m', DateMillis / 1000, 'unixepoch'),
COUNT(*)
FROM MyTable
GROUP BY 1
If you want to store a date, use date type. Sqlite may not have it. But please, do not use it as string! I would suggest you to store integer to store miliseconds sice epoch. Use bindLong() and such. Unfortunately, you have to make some computations yourself in code. Just compute first and last milisecond of each day. Then you would be able to use WHERE timestamp BETWEEN first_day_milisecond AND last_day_milisecond, using even indexes.
You can select min and max of timestamp to try only days between them.
If you need to do this frequently or over a lot of data, I suggest to store date in multiple columns as integers for year, month, day. Depends on what you have to do with time, miliseconds since midnight. Or more columns of hour, minute, second and miliseconds.
I think it is much easier to format string date from bunch of numbers than parsing those numbers from a string. Definitely easier to compare them inside database.

SQLite use year with date functions in where clause and group by

I am keeping date time values(Unix timestamps) in a "NUMERIC" format in SQLite table, the value is calculated through Java Date function:
new Date().getTime();
The values look like proper date/time when I load these in an Android program, but when I try to experiment with queries through SQLite data browser 2 beta the results are awkward. Numeric values are given below:
1391313058888
1391313104336
1391313175752
When I try to apply date function the SQLite data browser shows following for all three rows:
-1413-03-01 13:07:12
My query is
SELECT date(trxDateTime, 'unixepoch') from trx_log
I was trying to figure out how to get correct date values in the first place, once I got those then I believe I could figure a way to use it in where clause or group by.
Basically I am trying to show totals sales by year. Any help will be appreciated.
Your times are in milliseconds. Just convert them to seconds, and you'll be fine:
SELECT date(trxDateTime / 1000, 'unixepoch') from trx_log

Storing the Date and Time in a SQL Database on Android

I'm attempting to store 3 values in a database I've created on an android device. The values are NAME, DATE, and TIME. My question is thus: what is the best approach to fetch and store the current DATE and TIME values when they are inserted into the database?
So far I have identified two ways to do this, either by making system calls in android like //values.put(TIME, System.currentTimeMillis()); or using SQL functions like GETDATE(). But, which is better?
If I'm heading off in the wrong direction, please let me know and direct me towards the right direction.
Using the SQL functions will be more compatible with other tools using the same SQL engine.
Using text in ISO format YYYY-MM-DD hh:mm:ss.fff will be widely compatible and still sort properly.
The sqlite docs give these column type options for storing dates:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
You could use TEXT as described by Doug Currie, or you could use INTEGER using a java.util.Date. (I don't know why you'd use the REAL option.)
To use INTEGER, you could load and store dates something like this:
// build a date from a Cursor
Date d = new Date(cursor.getLong(DATE_FIELD_INDEX));
// add a date to an SQLiteDatabase
final ContentValues values = new ContentValues();
values.put(DATE_FIELD, d.getTime());
db.insert(TABLE_NAME, null, values);
This will be less readable in your database, but comparisons between dates (in your query) should be faster since comparing numbers is faster than strings. (Although I don't know much about the sqlite implementation.)

how to store a time value in SQLite database in Android?

I want to store a timevalue in an SQLite database in Android. My time value is in EditText, and when I click the save button I would like the time value to be stored in the database. And also I want to review the already-stored value in the database.
SQLite doesn't have a specific datatype for storing times, and leaves it up to you whether you want to store them as text, integers, or floating-point values, so you can establish whatever convention works best for you.
For your application where you want the time to be editable by the user I'd suggest looking into the DatePicker and TimePicker widgets, so that you don't have to worry about parsing and formatting the time as text, and then the Java Calendar class for converting the data from those into a simple value that you can put in the database (I'd suggest using the getTimeInMillis() method to convert it into a integer).
Sqlite + timestamp = Date and time functions
Sqlite + timestamp + android = Timestamp Class
Other options
create a column for each piece of info you wish to store (day, hour, min, second, etc)
convert time into long and store that instead. Use java.sql.Time

Categories

Resources