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);
}
}
根据您的喜好更改 String format
的列表是 这里.
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));
这篇关于Android - 使用光标适配器在 ListView 中格式化时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!