开发者

Query to convert from datetime to date mysql

开发者 https://www.devze.com 2023-02-05 08:34 出处:网络
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?

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 m开发者_如何学Cy 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.


Try to cast it as a DATE

SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED


Use the DATE function:

SELECT DATE(orders.date_purchased) AS date


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.


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');

Query to convert from datetime to date mysql


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
0

精彩评论

暂无评论...
验证码 换一张
取 消