简体   繁体   中英

MYSQL Fetch Date and Time Stored as String and ORDER BY

I have a specific reason for storing Date and Time in DataBase Table as String in below format

DateFmt = "dd-MM-yyyy";
TimeFmt = "hh:mm a";

Now while fetching I want to sort by converting the string to Date and Time and sort to display in TableView, so the row with newer ones come on top.

This wil work if we store as date and time,

ORDER BY `DATE` DESC, `TIME` DESC

How do we convert from String and use order by

Use str_to_date() :

order by str_to_date(date, '%d-%m-%Y')

I should add: I can think of no good reason for storing a date in that format in the database. You should be using the built-in date/time types. They exist for a reason.

If you do have to store a date as a string (which I have to do occasionally), you should use YYYY-MM-DD format. This is ISO standard, converts readily to a date, and sorts correctly.

I came with the solution like this :

SQL :

SELECT * FROM NamTbl
    ORDER BY STR_TO_DATE(CONCAT(DateCol,' ',TimeCol), '%d-%m-%Y %h:%i') DESC

SQLite :

"SELECT * FROM " + NamTblVar +
             " ORDER BY STRFTIME('%d-%m-%Y %h:%i'," + DateKolVar + "|| ' ' ||" + TimeKolVar + ") DESC;";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM