簡體   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