有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Android Room中带日期的java查询

我有一个表todo_db,其中有一列dueDate,我想运行一个查询来选择所有dueDate类似于给定日期的地方

我在Dao中写下了这个查询

    @Query("SELECT * FROM todo_db WHERE dueDate LIKE :givenDate")
    List<todoEnt> getGivenDate(Date givenDate);

为了使用它,我调用了数据库的一个实例,我使用了Calendar的一个实例,并使用了getTime()

Calendar c;
Date dateToday;

c = Calendar.getInstance();
dateToday = c.getTime();

datalist = db.Maindao().getGivenDate(dateToday);

我试过了

SELECT * FROM todo_db WHERE dueDate = :givenDate

SELECT * FROM todo_db WHERE dueDate < (strftime('%s', 'now'))

我很感激你能给我的帮助。非常感谢

编辑:

我有一个类型转换器,dueDate是Date

@Entity(tableName = "todo_db")
public class todoEnt {
    @PrimaryKey(autoGenerate = true)
    public int id;

    @ColumnInfo(name = "title")
    public String todoTitle;

    @ColumnInfo(name = "description")
    public String todoDescription;

    @ColumnInfo(name = "dueDate")
    public Date todoDueDate;

}


public class Convertors {
    @TypeConverter
    public Date fromTimeStamp(Long value){
        return value == null ? null : new Date(value);
    }

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

}

共 (1) 个答案

  1. # 1 楼答案

    在方法中使用long而不是date。请记住,内部文件室将日期存储为长文件

    所以你的刀里应该有

    @Query("SELECT * FROM todo_db WHERE dueDate = :givenDateInLong")
    getGivenDate(long givenDateInLong)  
    

    然后你的代码会像

    Calendar c;
    Date dateToday;
    
    c = Calendar.getInstance();
    dateToday = c.getTime();
    long dateTodayInLong = dateToday.getTime();
    
    datalist = db.Maindao().getGivenDate(dateTodayInLong);