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
Related
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)
So I'm trying to query all the same dates but this code won't work
SELECT * FROM schedTBL WHERE CONVERT(varchar, DueDateTime, 120) LIKE " + "'%"+ text + "%'"
it returns no such column:varchar
This looks like a SQL statement for SQL Server, not SQLite...
Assuming you are storing dates in field DueDateTime without the hour part, something like this should do:
SELECT * FROM schedTBL WHERE DueDateTime = '2016-09-24'
Or you'll need like if you also have hour values. That depends on how you are actually storing dates/times in your SQLite DB.
Try formatting the date in Java and send it as a parameter to your query.
SQLite doesn't handle dates like SQL Server.
See:
SQLite Date And Time Functions
In SQLite, date values would be formatted with the strftime() function, or for this particular format, with the date() function:
... WHERE date(DueDateTime) LIKE ...
But this works only for supported date formats.
If the values in your database use an unsupported format, your only choice is to convert them, or to try to match the actual string:
... WHERE DueDateTime LIKE ...
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();
}
I have a parameter, where user can choose for which period of time data should be stored.
I read it in days variable. Date and time, when record was added to the database is stored in KEY_DATE_ADDED, it is created like:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // sql date format
Date date = new Date();
initialValues.put(KEY_DATE_ADDED, dateFormat.format(date));
Then I do the following:
mDb.delete(DATABASE_TABLE,
"date(now) > date(" + KEY_DATE_ADDED + ",+" + days + " days)",
null);
and it doesn't work. Actual query (where part) looks like:
WHERE date(now) > date(date_added,+10
days)
What is incorrect here? Looks like instead of date_added something else should be here.
I wanted to use SQL data formatting to avoid re-formatting dates several times.
Is there any GUI for Android database to test SQL queries on the actual data?
ok, I should use date('now') > date('date_added','+10 days')
Keep in mind that may also need to periodically use the VACUUM command to actually reduce the size of the database.
http://www.sqlite.org/lang_vacuum.html
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");