using localtime on a date - android

I have a column in my SQLite database that stores time values in UTC. How do i get the count of distinct days?
The below gives a result based on the UTC days, which would be wrong in the local timezone :
select distinct(date(column)) from table
The below would consider the time as well, which would be wrong :
select distinct(datetime(column,'localtime')) from table
Would it make sense to convert the date to localtime as below :
select distinct(date(column,'localtime')) from table
I am not sure if using the localtime conversion on a date, as opposed to a datetime, has any effect.

The only difference between date and datetime is in the output format, not in any internal calculations.
(All five date/time functions behave the same in this regard.)

Related

Not able to get formatted date from database sqlite

I have a table with timestamp column and the values stored in timestamp column are like
20180608T002304.507Z , 20180608T001745.821Z, 20180608T001628.170Z, 20180608T001336.516Z
I would like to get timestamp in "YYYY-MM-dd" formate.
Used strftime() function , but no use
when I query strftime('%Y-%m-%d %H:%M', timestamp) getting null
Thanks in advance
This is not one of the supported time string formats. Change the values so that they contain the appropriate punctuation:
sqlite> SELECT date('20180608T002304.507Z');
sqlite> SELECT date('2018-06-08T00:23:04.507Z');
2018-06-08
Your issue is that strftime along with all the SQLite date functions require specific formats as listed below. 20180608T002304.507Z is not one of the formats, hence the null.
Note the following is based upon your query using strftime('%Y-%m-%d %H:%M', timestamp) as opposed to I would like to get timestamp in "YYYY-MM-dd" formate.
You have two options.
1. You could utilise the substr function e.g.
:-
substr(mytimestamp,1,4)||'-'||
substr(mytimestamp,5,2)||'-'||
substr(mytimestamp,7,2)||' ' ||
substr(mytimestamp,10,2)||':'||
substr(mytimestamp,12,2)
where mytimestamp is the column name
As an example, the following :-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mytimestamp);
INSERT INTO mytable VALUES('20180608T002304.507Z'),('20180608T001745.821Z'),('20180608T001628.170Z'),('20180608T001336.516Z');
SELECT
substr(mytimestamp,1,4)||'-'||
substr(mytimestamp,5,2)||'-'||
substr(mytimestamp,7,2)||' ' ||
substr(mytimestamp,10,2)||':'||
substr(mytimestamp,12,2)
FROM mytable;
results in :-
2. Alter the source data to match one of the acceptable/recognised formats.
This could be done using something based upon :-
UPDATE mytable SET mytimestamp =
substr(mytimestamp,1,4)||'-'|| -- Year
substr(mytimestamp,5,2)||'-'|| -- Month
substr(mytimestamp,7,2)|| -- Day
substr(mytimestamp,9,1)|| -- T (or space)
substr(mytimestamp,10,2)||':'||
substr(mytimestamp,12,2)||':'||
substr(mytimestamp,14)
;
This based upon the table that was created above.
After running the update then using :-
SELECT strftime('%Y-%m-%d %H:%M', mytimestamp) FROM mytable;
results in :-
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
In formats 5 through 7, the "T" is a literal character separating the
date and the time, as required by ISO-8601. Formats 8 through 10 that
specify only a time assume a date of 2000-01-01. Format 11, the string
'now', is converted into the current date and time as obtained from
the xCurrentTime method of the sqlite3_vfs object in use. The 'now'
argument to date and time functions always returns exactly the same
value for multiple invocations within the same sqlite3_step() call.
Universal Coordinated Time (UTC) is used. Format 12 is the Julian day
number expressed as a floating point value.
Formats 2 through 10 may be optionally followed by a timezone
indicator of the form "[+-]HH:MM" or just "Z". The date and time
functions use UTC or "zulu" time internally, and so the "Z" suffix is
a no-op. Any non-zero "HH:MM" suffix is subtracted from the indicated
date and time in order to compute zulu time. For example, all of the
following time strings are equivalent:
2013-10-07 08:23:19.120
2013-10-07T08:23:19.120Z
2013-10-07 04:23:19.120-04:00
2456572.84952685
In formats 4, 7, and 10, the fractional seconds value SS.SSS can have
one or more digits following the decimal point. Exactly three digits
are shown in the examples because only the first three digits are
significant to the result, but the input string can have fewer or more
than three digits and the date/time functions will still operate
correctly. Similarly, format 12 is shown with 10 significant digits,
but the date/time functions will really accept as many or as few
digits as are necessary to represent the Julian day number.
SQL As Understood By SQLite - Date And Time Functions

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.

How to convert milliseconds to date in SQLite

I store date from Calendar.getTimeInMilliseconds() in SQLite DB.
I need to mark first rows by every month in SELECT statement, so I need convert time in milliseconds into any date format using SQLite function only. How can I avoid this?
One of SQLite's supported date/time formats is Unix timestamps, i.e., seconds since 1970.
To convert milliseconds to that, just divide by 1000.
Then use some date/time function to get the year and the month:
SELECT strftime('%Y-%m', MillisField / 1000, 'unixepoch') FROM MyTable
Datetime expects epochtime, which is in number of seconds while you are passing in milliseconds. Convert to seconds & apply.
SELECT datetime(1346142933585/1000, 'unixepoch');
Can verify this from this fiddle
http://sqlfiddle.com/#!5/d41d8/223
Do you need to avoid milliseconds to date conversion or function to convert milliseconds to date?
Since sqlite date functions work with seconds, then you can try to
convert milliseconds in your query, like this
select date(milliscolumn/1000,'unixepoch','localtime') from table1
convert millis to seconds before saving it to db, and then use date function in sql query

Change a SQL server query to equivalent in SQLite

I have this query which works in SQL server:
Convert(datetime, [ChangedDate]) >= DATEADD(DAY, -3, CAST(GETDATE() AS DATE))
I want to make it work in Android SQLite database.
As far as I understood I need to use something like: date('now','+14 day') instead of DATEADD, but it gives me an error on datetime (it could be here Convert(datetime,...) in sqlite.
Can you modify this query in order to make it works on SQLite?
SQLite does not have a date data type. So you're not required to use convert or cast. A query like this would work:
select *
from table1
where col1 < datetime('now', '-3 days')
Example at SQL Fiddle.
For more details, see the SQLite manual:
1.2 Date and Time Datatype
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:
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.
Applications can chose to store dates and times in any of these
formats and freely convert between formats using the built-in date and
time functions.

SQLite Date Query In Android

I am using SQLite database for my application.
The Table Structure Goes Like :
_id : integer primary key
name : text
day : date
I am able to store date in format : dd-mmmmm-yyyy eg. 15-June-2011
But when i tried to retrieve all records filtered by date from the database it returns me null.
database.query(DATABASE_TABLE, new String[] { "strftime('%d-%mm-%Y',date('now'))","strftime('%d-%m-%Y',"+KEY_DAY+")" },
"strftime('%d-%m-%Y',date('now'))=" + KEY_DAY , null,null,null,null,null);
It didnt match with anyrow's date even though there were some matching dates.
I have already gone thru documentation of SQLite. But didn find any solution yet.
I want to have something like :
select * from table where day=curdate();
How can i do the same task in SQLite ?.
(Yes I am flexible to change the format of date stored in Dateabase)
What are other alternatives for the same task ?.
In java programming you can convert any date format into long (time in milliseconds) and viceversa. My opinion is while storing format the date into long format in java and then store long value of date in database. also while retrieving you can retrieve the long value and then format that as per your expected date format. I have been using this type of logic for several application.
Thanks
Deepak.
The function strftime('%d-%m-%Y',date('now')) returns a string with the month in numeric format (from 01 to 12). As far as I can tell from the docs, there is no format specifier to return the full name of the month.
I think you'll have to store your dates using numerical month specifiers instead of names.

Categories

Resources