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

而不是上面,你为什么不直接在 SQLIte 中使用函数strftime()呢?更清洁,更快。

于 2013-06-08T14:02:56.433 回答