英文:
How to display only dates with a certain year stored in Room database?
问题
我使用MVVM架构,并将日期以类似12.05.2020的格式存储在数据库中。我想获取所有具有特定年份(例如2020年)的日期。
我当前的DAO查询如下:
@Query("SELECT * FROM Sorted WHERE date = :date")
LiveData<List<Sorted>> getSortedWhereDateIs(String date);
如何仅从完整的日期中提取年份或月份?谢谢任何帮助。
英文:
I use an MVVM structure and store dates in a database in a format like 12.05.2020. I want to get all the dates, that have a particular year, 2020 for example.
My current DAO query looks like:
@Query("SELECT * FROM Sorted WHERE date = :date")
LiveData<List<Sorted>> getSortedWhereDateIs(String date);
How can I pick out only year or month from a whole date? Thanks for any help.
答案1
得分: 1
检查这是否有效 -
- 从用户输入中提取年份值
- 将年份传递给您的查询
@Query("SELECT * FROM Sorted WHERE YEAR(date) = :year")
LiveData<List<Sorted>> getSortedWhereDateIs(Integer year);
对于月份,您可以使用MONTH(fullDate)
。
英文:
Check if this works -
- Extract the year value from the user input
- Pass the year to your query
@Query("SELECT * FROM Sorted WHERE YEAR(date) = :year")
LiveData<List<Sorted>> getSortedWhereDateIs(Integer year);
For month you can use MONTH(fullDate)
答案2
得分: 1
你的查询应该类似于以下内容:
对于年份:
@Query("SELECT * FROM Sorted WHERE CAST(strftime('%Y', date / 1000,'unixepoch') AS INTEGER) = :yearId")
对于月份:
@Query("SELECT * FROM Sorted WHERE CAST(strftime('%m', date / 1000,'unixepoch') AS INTEGER) = :monthId")
更多细节可以查看这篇博客。
英文:
Your query must be something like that:
@Query("SELECT * FROM Sorted where CAST(strftime('%Y', date / 1000,'unixepoch') as INTEGER) = :yearId)
and for month:
@Query("SELECT * FROM Sorted where CAST(strftime('%m', date / 1000,'unixepoch') AS INTEGER) = :monthId")
for more details you can check this blog
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论