How to Order Room results by Date as String

大兔子大兔子 提交于 2019-12-13 04:27:02

问题


I have a room database. I have a column for date and it's saved as string.

I used this query for sort my column :

@Query("SELECT * FROM session WHERE class_id = :classId ORDER BY session_date ASC")
List<SessionEntry> getAllSessions(int classId);

Result :

    1398/11/25
    1398/11/29
    1398/12/5
    1398/2/14
    1398/4/25
    1398/6/17
    1398/6/30
    1398/7/9
    1398/9/14

but i want to sort like this :

    1398/2/14
    1398/4/25
    1398/6/17
    1398/6/30
    1398/7/9
    1398/9/14
    1398/11/25
    1398/11/29 
    1398/12/5

Is there any way I could order by Date as String without modifying the database structure ?


回答1:


in my case it is working as I have like float type formate :

  @Query("SELECT * FROM growthlogdata WHERE babyid = :childid Order By CAST(dateGrowth AS FLOAT) ASC")
List<SessionEntry> getAllSessions(int classId);



回答2:


First answer, don’t store dates as strings, use a proper date datatype.

However, if I understand correctly that your SQLite database hasn’t got a date datatype, @matdev is correct: The best solution is to change the format into yyyy-mm-dd. This conforms with ISO 8601 and will sort chronologically.




回答3:


I found a solution but it's not best.

This way is for when you can't change your Date Column from String to another type

List<SessionEntry> sessionEntries = mDb.sessionDao().getAllSessions(classId);
Collections.sort(sessionEntries, comparing(SessionEntry::convertStringToDate));

Session Entry :

public class SessionEntry {
    .
    .
    .
    public Date convertStringToDate() {
        try {
            return new SimpleDateFormat("yyyy/MM/dd").parse(getSessionDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}


来源:https://stackoverflow.com/questions/58181364/how-to-order-room-results-by-date-as-string

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