0

I've got a question about sorting the MySQL output in a column where my date ist stored. The format is "10.01.2014 - 16:01 - Fr.".

I've got a query is as followed:

SELECT * FROM `jtmpl2_chronoforms_data_test_reservierung` ORDER BY `res_date` ASC

The problem is, that it only orders the date with the first number. So for example "10.01.2014 - xxxx" is before "12.12.2013 - xxxx".

Any idea how i can solve this?

6
  • 8
    Yes, don't store your dates as strings. Commented Dec 10, 2013 at 16:02
  • Use real time datatypes for storing dates. Commented Dec 10, 2013 at 16:03
  • Use the mysql datetime field YYYY-MM-DD or you are in for lots of problems. Commented Dec 10, 2013 at 16:03
  • 1
    John's point is that there are specific data types for dates so that you can sort them properly; you can then use formatting commands in either mysql or php to display the date in the form you want. If your source data is storing the date as a string, you should use an ETL script to convert it to a datetime. Commented Dec 10, 2013 at 16:04
  • Store dates in the mysql date format. If you can't anymore, you still can think about sorting them through PHP using asort after querying them, even though it is NOT a really valuable solution. Commented Dec 10, 2013 at 16:06

2 Answers 2

2

You can use the STR_TO_DATE function to convert from string to a true date representation.

See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date

Something like this could you work (but you may need to play with the format):

SELECT * 
FROM jtmpl2_chronoforms_data_test_reservierung
ORDER BY STR_TO_DATE(res_date, '%M.%d.%Y %h:%i') ASC

The format string above is only a suggestion - be sure to check that you have a correct conversion from the string to the actual date it should represent.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution works for the date, but not the time. I've tried STR_TO_DATE(res_date, '%d.%m.%Y - %h:%i'), but it does not work. Do you have any solution for this?
Played with the format specifiers, and got the following to work: select str_to_date('10.01.2014 - 16:01 - Fr', '%m.%d.%Y - %H:%i' );. For the specifiers, see dev.mysql.com/doc/refman/5.0/en/….
0
SELECT * FROM `jtmpl2_chronoforms_data_test_reservierung` ORDER BY DATE(`res_date`) ASC

|| 

SELECT * FROM `jtmpl2_chronoforms_data_test_reservierung` ORDER BY DATE_FORMAT(`res_date`,'%Y%m%d') ASC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.