我正在撰寫一份報告,該報告將從 Room 資料庫中獲取過去 7 天的資料。這是我簡化的應用程式結構。
Entity Class:
@Entity(tableName = "cleaning")
data class Cleaning(
@PrimaryKey(autoGenerate = true)
val id: Long,
val task: String,
val timestamp: Date
)
型別轉換器:類 DateTypeConverter {
@TypeConverter
fun fromTimeStampToDate(timestamp: Long?): Date? {
return timestamp?.let {
Date(it)
}
}
@TypeConverter
fun fromDateToTimeStamp(date: Date?): Long? {
return date?.time?.toLong()
}
資料訪問物件類提取:
@Query("SELECT * from cleaning WHERE (timestamp=Calendar.getInstance().time - 7) ORDER BY id DESC")
fun readSevenDaysData(): LiveData<List<CleaningRecord>>
問題是(timestamp=Calendar.getInstance().time - 7)。當我使用 Calendar.getInstance().time 存盤日期時,我不知道如何提供過去 7 天的資料提取范圍
非常感謝任何正確方向的指導。
uj5u.com熱心網友回復:
我相信以下內容會滿足您的要求:-
@Query("SELECT * from cleaning WHERE CAST((timestamp / 1000) AS INTEGER) BETWEEN strftime('%s','now','-7 days') AND strftime('%s','now') ORDER BY id DESC;")
也就是說,時間戳存盤到毫秒,因此除以 1000 會將值減少到秒。
strftime('%s' ....以秒為單位回傳時間'now'回傳當前日期時間'-7 days'相應地修改值- 有關更全面的資訊,請參閱
Additionally using App Inspection the query
SELECT *, timestamp /1000 AS timetosecond, strftime('%s','now','-7 days') AS fromtime, strftime('%s','now') AS totime from cleaning WHERE CAST((timestamp / 1000) AS INTEGER) BETWEEN strftime('%s','now','-7 days') AND strftime('%s','now') ORDER BY id DESCwas run to further show a) how useful App Inspection can be and b) what the various parts do the query do with the actual data.
i.e. the above resulted in :-

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446901.html
- 有關更全面的資訊,請參閱
