Android - 使用光标适配器在ListView中格式化时间戳 [英] Android - Format Timestamp in ListView with Cursor Adapter
问题描述
我正在使用一个SimpleCursorAdapter来填充一个Android ListView,并且想知道如何从数据库获取所有的时间戳,每一个在DATE_DATE到人类可读的日期,也许是使用SimpleDateFormat?
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_DATE" into human readable dates, maybe 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);
我没有做过很多Java的工作,所以有更好的方法/任何方式这个?除了将预先格式化的日期存储在数据库中,除了手头之外吗?
I've not done much work with Java, so is there a better way / any way to do this? Other than storing the preformatted dates in the database before hand, that is?
推荐答案
您将不得不创建一个自定义CursorAdapter可以格式化您的时间戳。
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);
}
}
更改您的喜好的字符串格式
是此处。
然后您可以使用此适配器
You'd then use this adapter with
Cursor programDateCursor = mDbAdapter.loadProgramDates();
startManagingCursor(programDateCursor);
setListAdapter(new MyAdapter(this, programDateCursor));
这篇关于Android - 使用光标适配器在ListView中格式化时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!