mysql query - format date on output?

╄→гoц情女王★ 提交于 2020-01-21 09:43:25

问题


In my table, dates are stored like this: 2011-03-03T13:30:00

I'm trying to output dates like this: March 3, 2011 1:30 PM

I'd much rather work it into the query rather than use php to format it, but I'm having some difficulty doing that. Trying various iterations of DATE_FORMAT, but it's not giving me what I want, maybe because of the way it's being stored?


回答1:


You basically have two different operations you may need to perform when handling dates: date to string and vice versa. The functions you can use are DATE_FORMAT() and STR_TO_DATE(). Full reference can be found in the manual.

Usage example:

SELECT
    DATE_FORMAT(CURRENT_TIMESTAMP, '%d/%m/%Y %H:%i:%s'),
    STR_TO_DATE('31/12/2001 23:55:00', '%d/%m/%Y %H:%i:%s')

If your dates are not real dates but strings, you'll need to convert twice: from string to date and again from date to string:

SELECT
    STR_TO_DATE('2011-03-03T13:30:00', '%Y-%m-%dT%H:%i:%s'),
    DATE_FORMAT(STR_TO_DATE('2011-03-03T13:30:00', '%Y-%m-%dT%H:%i:%s'), '%M %e, %Y %l:%i %p')



回答2:


Use DATE_FORMAT:

DATE_FORMAT(date, "%M %e, %Y %h:%i %p")



回答3:


The MySQL date storage format is actually YYYY-MM-DD, but using the str_to_date() and date_format() functions you can accept and generate any date format required.


select DATE_FORMAT(DateTable.MyDate,'%d %b %y')
from DateTable

would return

04 Nov 08




回答4:


You should really use a DATETIME field for such things (and clean the input on the way in) rather than having to sort this out at the point of output.

Irrespective, you can simply use the DATE_FORMAT function to re-format your field into the format you require, although this might produce some un-expected results on a VARCHAR or CHAR field. (If so, you'll have to use STR_TO_DATE or failing that some various string functions to extract the date bits you require.)



来源:https://stackoverflow.com/questions/4596457/mysql-query-format-date-on-output

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