想要从数据库的给定日期范围中检索值

时间:2013-02-25 07:55:42

标签: android android-sqlite

我想以下列方式获取值:

我想获取当前周数的总值,我的代码在这里:

SimpleDateFormat weekDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, 1);
Date weekFirstDate = c.getTime();
String strWeekFirstDay = weekDateFormat.format(weekFirstDate);
Cursor weekCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strWeekFirstDay+"' AND '"+todays_date+"';", null);
int weekCounter = 0;
if(weekCursor.moveToFirst())
    weekCounter = weekCursor.getInt(0);
else
    weekCounter = 0;
weekCursor.close();

这是获取当前月份总数的代码:

SimpleDateFormat monthDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar c2 = Calendar.getInstance();
    c2.set(Calendar.DAY_OF_MONTH, 1);
    Date monthFirstDate = c2.getTime();
    String strMonthFirstDay = monthDateFormat.format(monthFirstDate);

    Cursor monthCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strMonthFirstDay+"' AND '"+todays_date+"';", null);
    int monthCounter = 0;
    if(monthCursor.moveToFirst())
        monthCounter = monthCursor.getInt(0);
    else
        monthCounter = 0;
    monthCursor.close()

这是正确的??因为它不能正常工作,意味着我得到错误的价值观。我也希望从星期一开始我的一周。有人会更正我的代码或建议一些新的代码。

1 个答案:

答案 0 :(得分:1)

以此格式存储所有日期,然后重试..

MM-dd-yyyy

Cursor monthCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strMonthFirstDay+"' AND '"+todays_date+"';", null);