how to convert a string to date in mysql?

2018-12-31 19:33发布

I have a string column which acts as a date and I want to select it as a date.

Is it possible?

My sample data format would be; month/day/year -> 12/31/2011

4条回答
荒废的爱情
2楼-- · 2018-12-31 19:39

Here's another two examples.

To output the day, month, and year, you can use:

select STR_TO_DATE('14/02/2015', '%d/%m/%Y');

Which produces:

2015-02-14

To also output the time, you can use:

select STR_TO_DATE('14/02/2017 23:38:12', '%d/%m/%Y %T');

Which produces:

2017-02-14 23:38:12

查看更多
不流泪的眼
3楼-- · 2018-12-31 19:46

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAYS

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

查看更多
唯独是你
4楼-- · 2018-12-31 19:48
STR_TO_DATE('12/31/2011', '%m/%d/%Y')
查看更多
琉璃瓶的回忆
5楼-- · 2018-12-31 19:55

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL

SELECT  STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM    table

say for example use the below query to get output

SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table

For String format use the below link

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

查看更多
登录 后发表回答