Comparing a date in a Room database

此生再无相见时 提交于 2021-02-11 12:19:03

问题


I have this Entry data class

@Entity(tableName = "entry")
@Typeconverters(DateConverter::class)
data class Entry(

    @PrimaryKey(autoGenerate = false)
    var id : String,
    var username : String,
    var type : String,
    var description : String,
    var category : String,
    var amount : Double,
    var date : String,
    var lastUpdate : String,
    var isDeleted : Boolean)
}

The date field contains a string that represents a date in the "yyyy-MM-dd" format, while the lastUpdate contains a string that represents a date in the "yyyy-MM-dd hh:mm:ss" format. If i store those variables as strings i cannot do SQL comparisons on them since Room does not support SQL's DATE() and DATETIME() datatype and thus queries like this:

@Query(SELECT * FROM entry WHERE date >= :fromDate AND date <= :untilDate)

Will not work properly. Is there any way to fix this?


回答1:


Well, I see 3 options.

  1. Since your date string is formatted in a nice hierarchical way (year, month, day), you should actually be able to use its natural String sort.

  2. If you need real date sort within a SQL query, you'll have to save your date as real date-field or integer field (Unix epoch timestamp)

  3. If it is okay to sort the date after fetching it from the DB or before storing it in the DB, make yourself familiar with TypeAdapter in Room. It's a simple conversion class where you can convert from String to DateTime and back.

To answer your second question on why such "common" data type is not supported out-of-the box, I can recommend this medium article:

SQLite is a loosely typed database system and stores all values as one of: NULL, INTEGER, TEXT, REAL or BLOB. You’ll notice that there is no special date or time type like you may find in other database systems.

Instead they provides the following documentation on how to store date/time values: SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

If you think about it further, the question arises: What is a common data type and where does "common" end. Of course, they could provide some TypeConverters, but on the other hand it's a few lines of code for each data type.

Here is an example for a TypeConverter from Date to String and back:

public class Converters {
  @TypeConverter
  public static Date fromTimestamp(Long value) {
    return value == null ? null : new Date(value);
  }

  @TypeConverter
  public static Long dateToTimestamp(Date date) {
    return date == null ? null : date.getTime();
  }
}


来源:https://stackoverflow.com/questions/62783462/comparing-a-date-in-a-room-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!