1

記事を日付順に並べ替えたい。そのためには、日付を文字列から日付形式に変換する必要があると思います。私のデートはFri,12 Feb 2012 12:23:32

私はこれをそのようにしようとしています:

private String formatDateTime(Context context, String timeToFormat) throws java.text.ParseException {

        String finalDateTime = "";

        SimpleDateFormat iso8601Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSSZ",Locale.UK);

        Date date = null;
        if (timeToFormat != null) {
            try {
                date =(Date) iso8601Format.parse(timeToFormat.trim());
            } catch (ParseException e) {
                date = null;
            }

            if (date != null) {
                long when = date.getTime();
                int flags = 0;
                flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
                flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
                flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
                flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

                finalDateTime = android.text.format.DateUtils
                        .formatDateTime(context, when
                                + TimeZone.getDefault().getOffset(when),
                                flags);
            }
        }
        return finalDateTime;
    }

その後 :

public Cursor getAllData() {// DBHelper.ROWID+" DESC"

        String buildSQL = null;

            try {
                buildSQL = "SELECT * FROM " + DBHelper.DATABASE_TABLE
                        + " ORDER BY " + formatDateTime(ourContext,DBHelper.DATE)+ " ASC";
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return ourDatabase.rawQuery(buildSQL, null);
    }

しかし、私はNullPointerExceptionを取得します

return ourDatabase.rawQuery(buildSQL, null);

別の方法:

public Cursor getAllData() {

        String buildSQL = null;

            try {
                buildSQL = "SELECT * FROM " + DBHelper.DATABASE_TABLE
                        + " ORDER BY " + formatDateTime(DBHelper.DATE)+ " ASC";
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return ourDatabase.rawQuery(buildSQL, null);
    }

    private Date formatDateTime(String timeToFormat) throws java.text.ParseException {

        SimpleDateFormat curFormater = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSSZ",Locale.ENGLISH); 
        Date dateObj = (Date) curFormater.parse(timeToFormat); 

        return dateObj;
    }
4

1 に答える 1

1

上記の代わりに、関数strftime()を SQLIte で直接使用しないのはなぜですか? はるかにクリーンで高速です。

于 2013-06-08T14:02:56.433 に答える