Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Room results by Date as String

I'm working on an app where Dates are entered in the Room database as Strings, with a SimpleDateFormat fixed to '%d/%m/%Y %H:%M:%S' (e.g. "26/12/2018 10:33:31").

Without changing the structure of the database, I'd like to query some results, ordered by date. This should probably look like this (inside a Dao):

@Query("SELECT * FROM results ORDER BY stringToDate(startTime) DESC LIMIT :count")
List<Results> getLast(int count);

Unfortunately, this throws a compile error: "no such function: stringToDate", no matter if the function exists, even if it is annotate as TypeConverter in due form.

Moreover, since String is accepted as a Room type, I'm not event sure I could use TypeConverter here to begin with.

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

like image 711
Dan Chaltiel Avatar asked Dec 21 '25 09:12

Dan Chaltiel


2 Answers

Try:

@Query("SELECT * FROM results ORDER BY strftime('%Y-%d-%m-%Y', startTime) DESC LIMIT :count")

Make sure that the format passed to strftime match your time format.

For reference formats can be found here: https://www.tutorialspoint.com/sqlite/sqlite_date_time.htm

like image 129
Don Ha Avatar answered Dec 24 '25 00:12

Don Ha


Can you try changing stringToDate(startTime) to datetime(startTime)?

Can you provide a sample of startTime object?

like image 39
Mahdi Khardani Avatar answered Dec 23 '25 23:12

Mahdi Khardani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!