Irgi Ahmad Maulana
Irgi Ahmad Maulana

Reputation: 107

How to get 7 days data with Room database

The problem is that the date field is string and not date, should I change this first?

If I change the data type, what should I insert to date field and how the format of the date?

The given date is like this

17 04 2020 (today / now date)

to

11 04 2020

Can you show me the example of the Dao query?

Upvotes: 0

Views: 869

Answers (1)

jbarat
jbarat

Reputation: 2470

A Date should be represented as a Long in the database. Then you can create a type converter like this:

class Converters {
    @TypeConverter
    fun fromTimestamp(value: Long?): Date? {
        return value?.let { Date(it) }
    }

    @TypeConverter
    fun dateToTimestamp(date: Date?): Long? {
        return date?.time?.toLong()
    }
}

Then you can query like this:

@Dao
interface UserDao {
    @Query("SELECT * FROM user WHERE birthday BETWEEN :from AND :to")
    fun findUsersBornBetweenDates(from: Date, to: Date): List<User>
}

Upvotes: 1

Related Questions