0

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!

5
  • what is the current format? Commented Apr 2, 2014 at 14:38
  • 1
    The two formats should simply be the same. If not, the SQlite database shouldn't accept it Commented Apr 2, 2014 at 14:39
  • @weeknie Actually I'm not going to save MySQL TIMESTAMP, but I need to save current TIMESTAMP in the form of MySQL Commented Apr 2, 2014 at 14:42
  • @HamidShatu There are many formats. I need it in 2014-04-02 20:04:05 format Commented Apr 2, 2014 at 14:44
  • @eMM...current TIMESTAMP is String or Date? Commented Apr 2, 2014 at 14:48

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

How would I do it this way please db.execSql("CREATE TABLE "+ TABLE_TODO + "("+KEY_CREATED_AT + " DATETIME" +")");
Ah, that's a different question. Somethign you need to know about SQLite is that it really only has 5 column types: INTEGER, REAL, TEXT, BLOB, and NULL. It may recognize other type names like varchar, but it translates that to a type it knows: TEXT. From the SQLite documentation: "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"
1

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

3 Comments

how to create the table with a DATETIME column in the format of yyyy-MM-dd HH:mm:ss please?
create table tbl1(id int primary key, dt datetime);
Then I have to insert crnDate for the column dt isn't it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.