在where子句中比较日期时,SQLite Query无法正常工作

时间:2015-04-24 16:08:14

标签: android android-sqlite

我想从SQLite表中获取两个日期之间的记录,但是当在where子句中比较日期时它不起作用,实际上它适用于用作条件的其他String列或者当没有指定where子句时,所以是在where子句中使用日期的任何其他方式。

cursor = db.rawQuery("SELECT min(activity_date), max(activity_date) FROM tbl_activity_details" , null);
if(cursor != null) {
    itemsList.clear();
    while(cursor.moveToNext()) {
        itemsList.add(cursor.getString(0));
        itemsList.add(cursor.getString(1));
    }
    cursor.close();
    try {
        fromDate = sdf.parse(itemsList.get(0));
        toDate = sdf.parse(itemsList.get(1));
    } catch(Exception e) {
        e.printStackTrace();
    }

    try {
        Toast.makeText(this, "here "+sdf.format(fromDate)+"  "+sdf.format(toDate), 5000).show();
        //Toasts 2015-04-23 2015-05-01
        String fd = sdf.format(fromDate);
        String td = sdf.format(toDate);

        cursor1 = db.rawQuery("SELECT * FROM tbl_activity_details WHERE activity_date BETWEEN '"+fd+"' AND '"+td+"'", null); 
        Toast.makeText(this, "here 1"+cursor1.getCount(), 5000).show();
        //Toasts here 1 10
        if(cursor1 != null) {
            while(cursor1.moveToNext()) {
                Toast.makeText(this, "here 2"+cursor1.getString(0), 5000).show();
            }

        } else {
            Toast.makeText(this, "No Record Found", 5000).show();
        }
        cursor1.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }

2 个答案:

答案 0 :(得分:1)

我问了一个类似的问题,答案可能会帮助你,here's这个问题。

答案中可能与您相关的快速摘录:

如果在SQLite中使用String作为数据类型,则必须将System.currentTimeMillis()格式化为日期格式“yyyy / MM / dd”。如果您使用其他格式,例如M / d / yyyy - >您将有日期字符串比较问题。有关M / d / yyyy格式,请参阅下面的问题:

"5/15/2015".compareTo("11/30/2015") ---> Return 4 > 0
--> means "5/15/2015" > "11/30/2015" --- Wrong

答案 1 :(得分:0)

日期可以像这样比较..这可能会对你有所帮助。

   select *  from MyTable 
   where mydate >= Datetime('2000-01-01 00:00:00') 
   and mydate <= Datetime('2050-01-01 23:00:59')
相关问题