我已經經歷了無數次的帖子,但仍然無法達到預期的效果。Android SQLite日期查詢
我的日期/時間戳作爲字符串存儲在SQLite數據庫,其中一個看起來像:太陽4月16日零時26分33秒GMT + 01:00 2017年
我想實現是隻檢索從最近48小時(現在到2天前)存儲在數據庫中的項目。下面的代碼,我已經放在一起,繼續返回超過48小時/ 2天的結果。
public Cursor searchInboxEmails(String search, String twoDaysAgo, String today) throws SQLException {
Cursor cursor = null;
try {
if (search != null && !search.trim().isEmpty()) {
String received = "Received";
search = "%" + search + "%";
String query = "SELECT * FROM " + TABLE_NAME_1
+ " WHERE " + MESSAGE_TYPE + " IN (?)"
+ " AND " + FROM_EMAIL + " LIKE (?) OR " + CC_EMAIL + " LIKE (?) OR "
+ SUBJECT + " LIKE (?) OR " + MESSAGE + " LIKE (?)"
+ " AND " + "DATETIME(" + DATE_RECEIVED + ") BETWEEN DATETIME(?) AND DATETIME(?)"
+ " ORDER BY " + _ID + " DESC";
String[] params = {received, search, search, search, search, twoDaysAgo, today};
cursor = database.rawQuery(query, params);
if (cursor != null) {
cursor.moveToFirst();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return cursor;
}
值「twoDaysAgo」和「今天」也格式的字符串,看起來一樣的存儲字符串(「DATE_RECEIVED」)。獲得所需功能的任何幫助都是非常有幫助的。
編輯: 我增加了一個附加列「時間戳」節省大紀元值(例如1492337028)及以下功能的偉大工程(只顯示了時間戳後事項):
String received = "Received";
String query = "SELECT * FROM " + TABLE_NAME_1
+ " WHERE " + MESSAGE_TYPE + " IN (?)"
+ " AND DATETIME(" + TIMESTAMP + ") >= DATETIME(?)"
+ " ORDER BY " + TIMESTAMP + " DESC";
String[] params = {received, twoDaysAgo};
cursor = database.rawQuery(query, params);
但是,當試圖在時間戳記之後搜索項目時,它會在時間戳記之前返回項目,因此如何修改以下函數以僅搜索時間戳記之後的項目?
String received = "Received";
search = "%" + search + "%";
String query = "SELECT * FROM " + TABLE_NAME_1
+ " WHERE " + MESSAGE_TYPE + " IN (?)"
+ " AND " + FROM_EMAIL + " LIKE (?) OR " + CC_EMAIL + " LIKE (?) OR "
+ SUBJECT + " LIKE (?) OR " + MESSAGE + " LIKE (?)"
+ " AND DATETIME(" + TIMESTAMP + ") >= DATETIME(?)"
+ " ORDER BY " + TIMESTAMP + " DESC";
String[] params = {received, search, search, search, search, twoDaysAgo};
cursor = database.rawQuery(query, params);
請勿在編輯的解決方案中使用DATETIME(),然後檢查它是否有效。 –