Nikitha
Nikitha

Reputation: 45

Retrieving the data from room database using date string as earlist first

I have a database with 5 columns and one of the column is date string of the format "dd/mm/yyyy hh:mm:ss". I want to fetch the data from DB based on the earliest date first.

Below is the query that I have used :

  @Query("SELECT * from database_table ORDER BY dateTime('%d/%m/%Y %H:%M:%S',date) DESC")
    fun getAllTransactions(): List<DataBaseItem>

With the above query I am receiving the data as it is and not as per the specified format. Please let me know how to achieve this without changing the database structure.

Upvotes: 0

Views: 717

Answers (1)

MikeT
MikeT

Reputation: 57053

The SQLite datetime function expects the first parameter to be a date, and the subsequent parameters to be valid modifiers as per:-

You are instead passing a format as the first parameter and the value from the column as a modifier (which it isn't).

The datetime returns a specific format i.e. YYYY-MM-DD HH:MM:SS.

IF you want a date to be returned as dd/mm/yyyy then you would have to use the strftime function so strftime('%d/%m/%Y %H:%M:%S',date). However, date MUST be in a format recognised by SQLite.

If the date is stored as dd/mm/yyyy then it is not a recognised format.

As such you need to format it accordingly to suit the ORDERing so

ORDER BY substr(date,7,4)||substr(date,4,2)||substr(date,1,2) DESC

Upvotes: 1

Related Questions