11

In Android, is it possible to insert a time stamp into a database using ContentValues? When I try to add it using something like this:

ContentValues args = new ContentValues();       
args.put(MY_DATE, my_date);

I get an error telling me that my_date needs to be a String. Any suggestions on how to achieve this?

Razor
  • 1,778
  • 4
  • 19
  • 36
Kevin Bradshaw
  • 6,327
  • 13
  • 55
  • 78

1 Answers1

15

Neither Date nor Calendar are valid things to put in a ContentValues. The most efficient format, I think, is to convert the Date to milliseconds (getTime()) and store that in an INTEGER column.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 2
    Note though, you can't use getInt() when retrieving the data, you need to use getDouble() (on the cursor). Java-ints arn't big enough to store timestamps (this game me a major headace a while ago). – Alxandr Aug 07 '10 at 23:15
  • 2
    Thanks for the responses. It seems that I can add the timestamp to the contentvalues as a string and that it inserts into the database as an sql timestamp, when I use mDb.insert(DATABASE_TABLE, null, args), no problem. – Kevin Bradshaw Aug 08 '10 at 12:19