Android从SQLite数据库中选择日期(存储为int)=今天?

时间:2015-06-24 18:01:31

标签: android sqlite strftime

我将日期以int格式存储在SQLite表中(即毫秒 - 从System.currentTimeMillis()派生)。我现在想查询日期等于今天日期的表中的所有行,但是下面的查询总是返回零,即使upload_history表中的file_uploaded_date至少设置为今天的日期20行。 谁能告诉我我的查询有什么问题?

String today = new SimpleDateFormat("d-MMMM-yyyy").format(new Date());
String sql = "SELECT COUNT(*) as uploaded_today from upload_history "
    + "WHERE strftime('%-d-%b-%Y',file_uploaded_date) = strftime('%-d-%b-%Y','" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
   int uploadedToday = cursor.getInt(cursor.getColumnIndex("uploaded_today"));
}

2 个答案:

答案 0 :(得分:1)

我说你的格式字符串不正确。

我在文档中没有看到%b参数。对于月份,您可能希望使用%m%-d似乎也不正确。请改用以下格式字符串:%Y%m%d

此外,您将一个格式不正确的字符串传递给查询,而不是int,并依赖sqlite来纠正它。相反,与SimpleDateFormat( "yyyyMMdd" )进行比较而不进行进一步转换。

您的代码将如下所示:

String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String sql = "SELECT COUNT(*) from upload_history "
    + "WHERE strftime('%Y%m%d',file_uploaded_date) = '" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
   int uploadedToday = cursor.getInt(0);
}

(请注意,如果只返回一列,则无需为其命名,只能访问结果的第一列。)

此外,请注意,此查询将在每次执行时导致表扫描,因为sqlite需要将所有纪元转换为字符串。你最好在表格中添加一个日期列,然后更新一次:

UPDATE upload_history 
   SET just_the_date = strftime('%Y%m%d',file_uploaded_date)

这将允许您使用LIKE运算符进行更快速的搜索,甚至按年或月搜索。如果您的表非常大,您可能也想在该列上放置一个索引。

答案 1 :(得分:0)

您可以在日期格式中将日期作为字符串添加为日期格式,如yyyy-mm-dd hh-mm-ss,并使用sql查询从数据库中检索时将其进行比较。