SQL date format convert? [dd.mm.yy to YYYY-MM-DD]

半城伤御伤魂 提交于 2019-12-28 04:08:50

问题


is there mySQL function to convert a date from format dd.mm.yy to YYYY-MM-DD?

for example, 03.09.13 -> 2013-09-03.


回答1:


Since your input is a string in the form 03.09.13, I'll assume (since today is September 3, 2013) that it's dd.mm.yy. You can convert it to a date using STR_TO_DATE:

STR_TO_DATE(myVal, '%d.%m.%y')

Then you can format it back to a string using DATE_FORMAT:

DATE_FORMAT(STR_TO_DATE(myVal, '%d.%m.%y'), '%Y-%m-%d')

Note that the year is %y (lowercase "y") in STR_TO_DATE and %Y (uppercase "Y") in DATE_FORMAT. The lowercase version is for two-digit years and the uppercase is for four-digit years.




回答2:


Use

SELECT CONCAT(
'20',
SUBSTR('03.09.13', 7, 2),
'-',
SUBSTR('03.09.13', 4, 2),
'-',
SUBSTR('03.09.13', 1, 2))

Fiddle demo.

More about formats you can read in the corresponding manual page. Tip: if this is about conversion value from non-datetime field - better to use DATE/DATETIME data type instead. However, this is a bad idea to operate with dates via string functions. Above there is a nice trick with STR_TO_DATE (will not repeat that code, updated to fit better)




回答3:


Dates are stored using an internal format. You can use the function date_format() to convert it to a string using a variety of formats. For yours in particular:

select date_format(`date`, '%Y-%m-%d')


来源:https://stackoverflow.com/questions/18597051/sql-date-format-convert-dd-mm-yy-to-yyyy-mm-dd

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