I am working with android + SQLite and DatePicker Widget.
The DatePicker does not format correctly for my SQLite insert commands. I.e, if the chosen date has a month or day less than 10, it does not insert the 0’s. For example if I choose the date “1st January 2010”, the format of the month and date is 1 and 1. This clashes with the usual SQL format of YYYY-MM-DD.
I tried to concatenate 0’s into the integers when they are less than 10 by casting them to strings and prefixing o’s by doing the following:
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
if(monthOfYear < 10)
{
String mm = Integer.toString(monthOfYear);
String m = "0" + mm;
mMonth = Integer.parseInt(m);
}
else{mMonth = monthOfYear;}
if (dayOfMonth <10)
{
String dd = Integer.toString(dayOfMonth);
String d = "0" + dd;
dayOfMonth = Integer.parseInt(d);
}
else{mDay = dayOfMonth;}
mYear = year;
updateDisplay();
}
};
// updates the date in the TextView
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay).append("")
);
selecteddate = (String) mDateDisplay.getText();
}
I was expecting this to convert 2010-1-1 to 2010-01-01. It doesnt though. Does anyone have have a simpler way of doing this so that I can get the Date into the correct format before sending it to the sqlite table?
Thanks in advance.
SQLite doesn’t have Date/Time data types (http://www.sqlite.org/datatype3.html), so the ” usual SQL format of YYYY-MM-DD” isn’t the usual, in this case.
There are several date time functions (http://www.sqlite.org/lang_datefunc.html) but you can avoid those, most of the time, by just using the INTEGER data type on your date/time column and storing the epoch stamp (http://en.wikipedia.org/wiki/Unix_time).
DatePickerreturns separate values for year/month/day of month, and month is zero-indexed. This is because it’s intended to work withCalendar(as evil as that may be). So with an INTEGER column, and something like this, you can store and retrieve date/times fine:Then store the datePubStamp in the INTEGER column.
To restore a
Calendarjust useCalendar.setTimeInMillis(<value_from_integer_db_column>). And, you can of course get aDatefrom aCalendarwithgetTime(), and then format withSimpleDateFormat, etc.