Query to convert from datetime to date mysql

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I am trying to get the date portion of a datetime field. I know I can get it with date_format, but that returns a string or "varchar" field. How can I convert the result to date and not as varchar?

This is my query returning the varchar:

(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date   

I tried several combinations from this question, but could not make it to work:

mysql query - format date on output?

Any help is appreciated.

回答1:

Try to cast it as a DATE

SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED 


回答2:

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date 


回答3:

Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT() function returns a string, not a date. When you wrote

(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date  

I think you were essentially asking MySQL to try to format the values in "date_purchased" according to that format string, and instead of calling that column "date_purchased", call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format() returns a string, not a date.)

I don't think that's what you wanted to do, but that's what you were doing.

Don't confuse how a value looks with what the value is.



回答4:

syntax of date_format:

SELECT date_format(date_born, '%m/%d/%Y' ) as my_date FROM date_tbl      '%W %D %M %Y %T'    -> Wednesday 5th May 2004 23:56:25     '%a %b %e %Y %H:%i' -> Wed May 5 2004 23:56     '%m/%d/%Y %T'       -> 05/05/2004 23:56:25     '%d/%m/%Y'          -> 05/05/2004     '%m-%d-%y'          -> 04-08-13 


回答5:

I see the many types of uses, but I find this layout more useful as a reference tool:

SELECT DATE_FORMAT('2004-01-20' ,'%Y-%m-01'); 



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!