Android - timestamp format in ListView with cursor adapter

I am using a SimpleCursorAdapter to populate an Android ListView, and I was wondering how can I get all the timestamps I get from the database, each on DATE_DATE, on human readable dates, possibly using SimpleDateFormat?

Cursor programDateCursor = mDbAdapter.loadProgramDates(); startManagingCursor(programDateCursor); String[] from = new String[]{ "DATE_DATE" }; int[] to = new int[]{ R.id.text1 }; SimpleCursorAdapter programDates = new SimpleCursorAdapter(this, R.layout.program_date, programDateCursor, from, to); setListAdapter(programDates); 

I haven't worked much with Java, so is there a better way / any way to do this? Besides storing pre-formatted dates in a database before it was?

+8
java android date timestamp android-listview
source share
3 answers

You will need to create a custom CursorAdapter to be able to format your timestamps.

 public class MyAdapter extends CursorAdapter { private final LayoutInflater mInflater; public MyAdapter(Context context, Cursor cursor) { super(context, cursor, false); mInflater = LayoutInflater.from(context); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(R.layout.program_date, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { long time = cursor.getLong(cursor.getColumnIndex("DATE_DATE")) * 1000L; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); String format = "M/dd h:mm a"; SimpleDateFormat sdf = new SimpleDateFormat(format); String dateString = sdf.format(cal.getTime()); ((TextView) view.findViewById(R.id.text1)).setText(dateString); } } 

List of String format changes to your taste here .

Then you use this adapter with

 Cursor programDateCursor = mDbAdapter.loadProgramDates(); startManagingCursor(programDateCursor); setListAdapter(new MyAdapter(this, programDateCursor)); 
+16
source share

Save Unix era dates as INTEGER in an SQLite database. Then, in Java, initialize them with new Date(value) (or value*1000 , I'm not sure) and use SimpleDateFormat to format the dates in the adapter list.

I think this is the most convenient way for the limited information you provide.

0
source share

It was easier for me to do the following:

 SimpleDateFormat oldTime = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat newTime = new SimpleDateFormat("hh:mm:ss a"); String stringTime; try { String reformattedStr = newTime.format(oldTime.parse(stringTime)); } catch (ParseException e) { e.printStackTrace(); } 
0
source share

All Articles