Android - Format Timestamp in ListView with Cursor Adapter

前端 未结 3 531
迷失自我
迷失自我 2021-01-05 04:57

I am using a SimpleCursorAdapter to populate an Android ListView, and was wondering how I should go about getting all of the timestamps I get from a database, each in \"DATE

相关标签:
3条回答
  • 2021-01-05 05:37

    I found it easiest 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 讨论(0)
  • 2021-01-05 05:49

    You're going to have 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);
        }
    }
    

    The list to change the String format to your liking is here.

    You'd then use this adapter with

    Cursor programDateCursor = mDbAdapter.loadProgramDates();
    startManagingCursor(programDateCursor);
    
    setListAdapter(new MyAdapter(this, programDateCursor));
    
    0 讨论(0)
  • 2021-01-05 05:49

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

    I think that's the most convenient way for the limited information you've provided.

    0 讨论(0)
提交回复
热议问题