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

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");

Related

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)

Sqlite sorting by date column

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.

Save SQLite TIMESTAMP in the format of MySQL TIMESTAMP, Android

I want to save current TIMESTAMP to a SQLite database in Android.
But it should be in MySQL TIMESTAMP format which is 2014-04-02 20:04:05
How to make it in db.execSQL();
Please help!
Have a look at SQLite date and time functions. You would do something like
strftime(%Y-%m-%d %H:%M:%S, 'now') in your SQL string. This particular format also has a shortcut: datetime('now')
db.execSql("insert into table (column) values ( datetime('now') )");
My preference though is to simply store the current time as a long, which you can then format any way you like (or any way the user likes, or any way the system defaults to showing dates/times).
You should use the following date format in order to insert dates/times in SQLite:
DateFormat dateFormatISO8601 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
and retrieve in string as below:
String crntDate = dateFormatISO8601.format(new Date());
P.S. Make sure your column is of type DATETIME

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();
}

Issues in storing and retrieving data from sqlite in android

I am trying to retrieve data from the database with the following query:
select * from Oil Where date(DDate)=date('2012-08-07');
where DDate is one of the column in the Oil table with datatype text.I get the Arrayindexoutofboundsexception. I found that it is not returning any value the count is 0.
can anyone help me with this.What i am actually trying is to do is store date value in the table.I couldn't find which datatype should be used to save date,from the sqlite site is that it doesn't have a particular datatype for date and time.
SQL Server comes with the following data types for storing a date or a date/time value in the database:
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MM:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS
select * from Oil Where date(DDate)=date('2012-08-07');
can be
select * from Oil Where DDate='2012-08-07';
If you have DDate in the date format 'yyyy-MM-dd' then you can directly compare the date using
select * from Oil Where DDate='2012-08-07';
else if you have DDate in the date format 'yyyy-MM-dd HH:mm:ss' then the query looks like this
select * from Oil Where date(DDate)='2012-08-07';
If you are saving date in sqlite database and you have to perform date operations like sorting or using date() and time() functions then you have to use the 'yyyy-MM-dd HH:mm:ss' date format.
Datatype doesn't matter for sqlite.

Categories

Resources