1

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 ?

Nima Khalili
  • 251
  • 7
  • 18

3 Answers3

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);
bugfreerammohan
  • 1,471
  • 1
  • 7
  • 22
1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

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;
    }
}
Nima Khalili
  • 251
  • 7
  • 18