Java – Android java datetime value from String to Long to String issues

Android java datetime value from String to Long to String issues… here is a solution to the problem.

Android java datetime value from String to Long to String issues

Regular reader, first time poster.

In Android, a date is captured from a date picker and stored as a string in sqlite. Sorting by date doesn’t work because they’re strings (unless I’m doing it wrong.)

I’ve searched this issue for about 5 days and it looks like there should be a way to capture a date from a date picker, convert it to Long, store it as Long in sqlite, select and sort Long date values, and then convert Long back to the “mm/dd/yyyy” string for display. I’ve tried various combinations of parsing statements, Dates, FormatDates, etc., but have no luck at all.

My actual application process is:
At the start of the activity, get today’s date and display it in a button that calls the date picker.
Capture a new date from the date picker (if one is entered), save it as long to sqlite.
When you open an activity that displays a record ListView, select from sqlite (long) with date sorting to convert the long integer to a “mm/dd/yyyy” string to display in the ListView.

Would appreciate if someone could point me to my code example – thanks!



After hours of fumbling, the solution was a mixture of the given answer and some other stuff:

// variables declared
private int mYear;
private int mMonth;
private int mDay;

 datepicker declared and listened for
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;

 converting the datestring from the picker to a long:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, mDay);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.YEAR, mYear);
Long lDate = c.getTime().getTime();

The formatting that worked on the trip back from long to string 
 (I spent hours with SimpleDateFormat strings, years that were off by 1500, etc.):
String DateFormatted = DateFormat.getDateFormat(getApplicationContext()).format(helper.getDate(c));  helper.getDate(c) is just the passing back of the Long date from my SELECT statement

Forum newbie – I tried to vote what I thought was useful, but I don’t have enough prestige points yet.

Related Problems and Solutions