0

Is there any way to convert string to timestamp in MySQL?

For example I have string 01-05-2016 10:22 am which needs to be fetch with order by desc .

is it possible to sort that ?

5
  • 1
    What date is that? Is that the 1st of May or the 5th of January? Commented Dec 1, 2017 at 11:00
  • My database data type in varchar .. it fetch like 02-26-2015 10:40 am in order_date field .. i want to sort that field desc .. how to ? Commented Dec 4, 2017 at 4:46
  • Best option is for you to change from a varchar to a date/time datatype; then you can just apply a simple ORDER BY clause Commented Dec 4, 2017 at 8:00
  • not possible .. the requirement is store data as this format ( mm-dd-yyyy hh:mm a ) and fetch order by desc Commented Dec 5, 2017 at 5:10
  • @G Roy - Then you should be saying that the requirement is bad..... what is the business justification for treating strings as dates instead of using actual dates? Commented Dec 5, 2017 at 7:57

2 Answers 2

0

use order by function in SQL

SELECT * FROM table_name order by datetime DESC;

this will return values in descending order to php. no need to be sorted again.

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

Comments

0

UNIX_TIMESTAMP does the trick.

and

If you want to use the AM/PM notation, you will need to use STR_TO_DATE.

SELECT UNIX_TIMESTAMP(
    STR_TO_DATE(' 2016-05-01 10:22 am', '%Y-%m-%d %h:%i%p')
);

1 Comment

..its not working with SELECT UNIX_TIMESTAMP( STR_TO_DATE(' 2016-05-01 10:22 am', '%Y-%m-%d %h:%i%p') );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.