我想从当前日期获取数据的最后7个日期我现在将当前日期存储为字符串现在如何使用查询获取数据的最后7个日期?目前我的代码从降序返回我的最后20个数据现在我想只显示最近7天的数据,那么我该怎么办?
public class JobSchema extends BackBaseActivity {
List<JobSchmeModel> jobarr, missedarr;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.jobsschema);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm");
String formattedDate = df.format(c.getTime());
DatabaseHandler db = new DatabaseHandler(JobSchema.this);
jobarr = db.getALLCompJobs();
public class DatabaseHandler extends SQLiteOpenHelper {
String CREATE_COMPLETED_TABLE = "CREATE TABLE " + TABLE_COMPLETED_JOBS
+ "(" + KEY_COMPID + " INTEGER PRIMARY KEY," + KEY_TIMEJOB
+ " TEXT," + KEY_PICK + " TEXT," + KEY_DEST + " TEXT,"
+ KEY_FARE + " TEXT" + ")";
public List<JobSchmeModel> getALLCompJobs() {
List<JobSchmeModel> compjobsList = new ArrayList<JobSchmeModel>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_COMPLETED_JOBS+ " ORDER BY
"+KEY_COMPID+" DESC LIMIT 20";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
JobSchmeModel jobmodel = new JobSchmeModel();
jobmodel.setTime(cursor.getString(1));
jobmodel.setPick(cursor.getString(2));
jobmodel.setDestination(cursor.getString(3));
jobmodel.setFare(cursor.getString(4));
// Adding contact to list
compjobsList.add(jobmodel);
} while (cursor.moveToNext());
}
db.close();
return compjobsList;
}
答案 0 :(得分:2)
尝试在7天之前获取日期。
Calendar calender = Calendar.getInstance();
calender.add(Calendar.DAY_OF_MONTH, -7);
Date date = new Date();
date.setTime(calender.getTimeInMillis());
SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yy HH:mm");
String dateBefore7day = postFormater.format(date);
现在您的查询将是
String selectQuery = "SELECT * FROM " + TABLE_COMPLETED_JOBS + " WHERE " + KEY_TIMEJOB + ">=" + dateBefore7day + " ORDER BY "+KEY_COMPID+" DESC";
修改强>
要获取过去7天到今天之间的数据,如果您有未来的日期数据(当前日期之后的日期数据),那么您需要使用此数据。
String selectQuery = "SELECT * FROM " + TABLE_COMPLETED_JOBS + " WHERE " + KEY_TIMEJOB + ">=" + dateBefore7day + " AND " + KEY_TIMEJOB + "<=" + currentDate + " ORDER BY "+KEY_COMPID+" DESC";