Sending date and time information from Android to MySQL

Dates always seem to trip me up. The app that I am currently working on needs to send records from Android to a MySQL back end. The records contain date and time information. The records initially go into a SQLite db on the phone. From there they are read and sent to the back end one at a time and cancelled off the list when sending has been successful. So the problem comes down to putting a date and time into sqlite. Taking that date and time out and sending it across the network to be inserted into MySQL. Here is a synopsis of what I did to get this to work:
Create a table on sqlite (column types are largely irrelevant here, so just leave them out).
Create a table on mysql (the target) and specify a column type of timestamp for the date and time info.
Create a java.util.Date object to get the current time. Using a SimpleDateFormatter format this for insertion into the sqlite db.
Next read this row back.
Send this value across the network.
At the Mysql end use a prepared statement to do the insert and set the value of the date and time column like this:

stmt.setTimestamp(4, new java.sql.Timestamp(SDF.parse(phoneTime).getTime()));


That's it. If you try to use a java.sql.Date type for the insert you lose the time information. Otherwise that works fine. 
This is better than just inserting strings as you can now do stuff like order by that column. If it is strings, that is a much trickier proposition.

Comments

Popular posts from this blog

Building a choropleth map for Irish agricultural data

Early Stopping with Keras

AutoCompleteTextView backed with data from SQLite in Android