繁体   English   中英

Android - 带有光标适配器的ListView格式时间戳

[英]Android - Format Timestamp in ListView with Cursor Adapter

我正在使用SimpleCursorAdapter来填充Android ListView,并且想知道我应该如何获取从数据库获得的所有时间戳,每个时间戳在“DATE_DATE”到人类可读日期,也许使用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);

我没有做过很多Java工作,所以有更好的方法/任何方式来做到这一点吗? 除了事先将预先格式化的日期存储在数据库中,这是什么?

您将不得不创建自定义CursorAdapter以便能够格式化时间戳。

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);
    }
}

根据自己的喜好更改String format的列表就在这里

然后你用这个适配器

Cursor programDateCursor = mDbAdapter.loadProgramDates();
startManagingCursor(programDateCursor);

setListAdapter(new MyAdapter(this, programDateCursor));

我发现最简单的做法如下:

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();
        }

在SQLite数据库中将Unix纪元日期存储为INTEGER类型。 然后在Java中,使用new Date(value) (或value*1000 ,我不确定)初始化它们,并使用SimpleDateFormat格式化列表适配器中的日期。

我认为这是您提供的有限信息的最便捷方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM