Android SQLite数据库 - 按日期排序

时间:2013-06-08 13:57:41

标签: android sqlite

我想按日期对文章进行排序。为此,我想我必须将我的日期从字符串转换为日期格式。 我的约会对象是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;
    }

1 个答案:

答案 0 :(得分:1)

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