Monday, October 22, 2012

Store Date formatted data on sqlite3 with Android

When your android app needs to store data with sqlite database, usually date formatted data needs to be stored for most of the cases. However, from the official document of about the supported datatypes, we know it's better to have the well formatted text for the to be stored date.

So I made a little dig on this problem.
1st, the text of date stored in sqlite database is formatted as: "YYYY-MM-DD HH:MM:SS.SSS"

2nd, to make sure everything follows that format, you need to create a formatter first.

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
Here, DateFormat is from class: java.text.DateFormat
Do Not use the class from Android. Since DateFormat class give you the chance to convert string to date and vice verse.

3rd, convert a database stored string date to a Date object.

Date date = formatter.parse(string);

4th, Convert a Date object to one database date format required string.

String string = formatter.format(date);