Sqlite sorting by date column - android

I am storing date in ISO8601 format example 2015-04-15T10:54:14Z in sqlite table, I want youngest date from table. below are the dates in my sqlite table
2015-04-15T10:54:14Z
2015-04-15T10:54:115Z
2015-04-15T10:54:216Z
2015-04-15T10:54:320Z
2015-04-15T10:54:422Z
I am trying below query:
SELECT * FROM Table1 ORDER BY datetime("date_column") DESC ;
but I am not getting appropriate result.

ISO 8601 datetime stamps normalized to UTC have the nice property that the alphabetical (lexicographic) order is also temporal order.
You don't need the datetime(), you can just ORDER BY date_column DESC to sort them newest first, and you can add LIMIT 1 to get just the newest one.

Update your query to this:
SELECT * FROM Table1 ORDER BY date_column DESC LIMIT 1

use this method to put date column in your db:
public String getDatetime(){
//get time and date
Calendar c=Calendar.getInstance();
CharSequence s = DateFormat.format("yyyy-MM-dd HH:mm:ss", c.getTime());
//convert it to string array
return s.toString();
}
then use your query as you used before, cause datetime() accepts specific formatts.

Related

Comparing dates in android sqlite database

I'm comparing two dates in android sqlite database
I stored dates in the format
YYYY-MM-DD
Cursor cursor=db.rawQuery("SELECT * FROM "+tableName+" WHERE SALESDATE BETWEEN '2020-1-01' AND '2020-2-01';",null);
It gives result with dates of month 10, 11 and 12 along with the dates between above specified dates.
I would like to know if it is a bug or is there any mistake in my code.
The problem here is that your date literals are in a non standard (and likely incorrect) format. Appreciate that the following inequality holds true:
'2020-10-01' > '2020-1-01' AND '2020-10-01' < '2020-2-01'
This is true because the text 10 is lexicographically larger than just 1, but also less than 2. To avoid this problem, use proper date literals:
String sql = "SELECT * FROM " + tableName + " WHERE SALESDATE BETWEEN '2020-01-01' AND '2020-02-01';"
Cursor cursor = db.rawQuery(sql, null);
Note that SQLite does not actually have a formal date type. Thus, it is very important to always store your dates in SQLite using a proper ISO format.
You should store your Date as long value in database. Simple new Date().getTime() gives you this value and new Date(long value) returns it back. So you can make such queries easy.
But what I can suggest is to:
Export your table to CSV,
Change the date values to a proper SQLite TimeString and
Re-import the CSV after deleting the original table.
Then, you can run a query like:
SELECT * FROM tableName WHERE SALESDATE BETWEEN '2020-01-01 00:00:00' AND '2020-02-01 23:59:59'

Order By datetime column SQLite

I'm using a sqlie database wich have a datetime column, i stored values of the datetime column with format "yyyy-MM-dd HH:mm" but when i want to select values from Database and order by the datetime column, it gives me a wrong order.
SELECT id_user FROM RDV WHERE id_user= ? ORDER BY datetime(Date) DESC
i added datetime(Date) just to check if it works but it didn't work also
Acually i made in error, tha dates where in format "dd-MM-yyyy HH:mm" and i must put them in format yyyy-MM-dd HH:mm
What is the column name?
If it's called Date, just remove the call to datetime():
order by Date desc (or the name of the field if different)

How insert a date and time in sqlite from the current date and time of the system? [duplicate]

I want to create a table in SQLite in which one of the field is for date, in which date and time of current instance should save. Which data type should I use?
I'm planning to use 'timestamp'. How to insert current timestamp value to the field? Also how to write content values for this date field?
SQLite supports the standard SQL variables CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP:
INSERT INTO Date (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
The default data type for dates/times in SQLite is TEXT.
ContentValues do not allow to use generic SQL expressions, only fixed values, so you have to read the current time in Java:
cv.put("LastModifiedTime",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
INSERT INTO Date (LastModifiedTime) VALUES(DateTime('now'))
Use this site for further reference.
To get the current local(system) time, add the 'localtime' option:
select datetime('now', 'localtime');
I'm using timestamps a lot in my app. For me the best way to keep the timestamp is to convert it in milliseconds. After that it is easy to convert it to any locale.
If you need the current time use System.currentTimeMillis().
Content values are easy to use, you just and field and value, like:
ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());
Since SQLite 3.38.0, there is a unixepoch() function that returns UNIX timestamp in integer. Does the same thing as strftime('%s').
References:
release log draft
check-in
In my case i wanted to have a timestamp with fractions of a second.
How to get fractions of a second?
To get a value with fractions of a second the following worked with sqlite and .net-core using ado.net
INSERT INTO YourTable (TimeStamp)
VALUES (strftime('%Y-%m-%d %H:%M:%S:%s'))
CURRENT_TIMESTAMP has only seconds
The built in keyword CURRENT_TIMESTAMP has only a precision of YYYY-MM-DD HH:MM:SS like this
SELECT 'A ' as example, (strftime('%Y-%m-%d %H:%M:%S:%s')) as Better_TimeStamp
, 'With fractions of a seccond' as comment
UNION ALL
SELECT 'B ', CURRENT_TIMESTAMP
, 'only YYYY-MM-DD HH:MM:SS without fractions of a seccond'
This is explained on CREATE the DEFAULT clause
If the default value of a column is CURRENT_TIME, CURRENT_DATE or
CURRENT_TIMESTAMP, then the value used in the new row is a text
representation of the current UTC date and/or time.
The format is
HH:MM:SS for CURRENT_TIME
YYYY-MM-DD for CURRENT_DATE
YYYY-MM-DD HH:MM:SS for CURRENT_TIMESTAMP
Example to use it in c#
The following is based on bulk insert in sqlite with ado.net
public static void InsertBulk(SqliteConnection connection)
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var command = connection.CreateCommand();
command.CommandText =
#"INSERT INTO BulkInsertTable (CreatedOn, TimeStamp)
VALUES ($createdOn, strftime('%Y-%m-%d %H:%M:%S:%s'))";
var parameter3 = command.CreateParameter();
parameter3.ParameterName = "$createdOn";
command.Parameters.Add(parameter3);
// Insert a lot of data
// calling System.DateTime.Now outside the loop is faster
var universalTime = System.DateTime.Now.ToUniversalTime();
for (var i = 0; i < 15_000; i++)
{
parameter3.Value = System.DateTime.Now.ToUniversalTime();
// faster
// parameter3.Value = universalTime;
command.ExecuteNonQuery();
}
transaction.Commit();
}
connection.Close();
}

how to do date comparision through sql query?

how to compare dates .
for example my date format is 2011/10/12(YYYY/MM/DD).
I'm having some date records in database .i want some record greater than particular date.
for example :
String compareDate=2011/10/16;
select * from testtable where date>compareDate;
how to get least date and highest date through database query.
in sqlite is there any method to compare dates.
Thanks in Advance
Push the date to query in right format
select * from testtable where date > '2011-10-16';
more
Mysql Compare two datetime fields
http://dev.mysql.com/doc/refman/5.0/en/using-date.html
http://www.java2s.com/Code/SQL/Date-Time/Comparedateinwhereclause.htm
Before going to execute query, compareDate should be in this ("yyyy-MM-dd") format,
then try this query
select date from testtable where date > 'compareDate' order by date desc;
the above query order the date by descending order. The first row of cursor will have the max date.

sqlite convert 'dd.MM.yyyy' formated String to date

i have a sqlite database on my android, whith a datetime column, that contains a date with the Format dd.MM.yyyy.
It's not my Database, I'm niot able to change the Dateformat.
I want to compare the date in the database with a String, which is representing a secon date, but everything I tryed failed.
How can I convert this column to a valid, compareable date?
date(), dattime() sdfttime() everything returns NULL.
I searched on google for "sqlite3 date ddmmyyyy" and this post is the best solution (and the only one that worked for me amongst the posts listed on the bottom):
Problem:
A SQLite table contains dates in the format DD/MM/YYYY and need to be converted to SQLite native format YYYY-MM-DD
Problem Example:
sqlite> select id, calendar_day from tbl1;
id;calendar_day
4248281;2011-06-19
4248282;2011-06-19
4248283;19/06/2011
4248284;19/06/2011
Solution Example:
sqlite> update tbl1 set calendar_day = substr(calendar_day, 7) || "-" || substr(calendar_day,4,2) || "-" || substr(calendar_day, 1,2) where id>4248282;
Result Example:
sqlite> select id, calendar_day from tbl1;
id;calendar_day
4248281;2011-06-19
4248282;2011-06-19
4248283;2011-06-19
4248284;2011-06-19
Thank you all!
Other posts inspected:
Sqlite convert string to date
SOLite:Date formatter in SQLite
How can I convert datetime to date format in SQLite?
Sqlite convert string to date
How to convert a DD-MM-YYYY date format string into a YYYY-MM-DD date format string or into a NSDate object in Objective-C?
Try this query to change the column to the proper format for a text-date (assume table named table and column named date):
update table set date = substr(date, 7) || "-" || substr(date,4,2)
|| "-" || substr(date, 1,2);
You can also turn this around into a where clause per this answer.
Do you want do this in the database (SQL) or in program code? In Java you may use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date d = sdf.parse("21.03.1997");

Categories

Resources