Android select 来自 SQLite 数据库,其中日期(存储为 int)= 今天?

Android select from SQLite database where date (stored as int) = today?

我将日期以 int 格式存储在 SQLite table 中(即毫秒 - 来自 System.currentTimeMillis())。我现在想查询 table 中日期等于今天日期的所有行,但下面的查询总是 returns 零,即使 file_uploaded_date 在 upload_history table 在至少 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"));
}

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

我在文档中没有看到 %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);
}

(请注意,如果您 return 只有一列,则不必为其命名,只需访问第一列即可获得结果。)

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

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

这样您就可以使用 LIKE 运算符进行更快的搜索,甚至可以按年或按月进行搜索。如果您的 table 非常大,您可能还想在该列上放置一个索引。

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